Showing posts with label abstract class. Show all posts
Showing posts with label abstract class. Show all posts

Saturday, September 1, 2012

Abstraction and Abstract Class in java


Abstraction: Abstraction is act of representing data without including background details.

In java it can be achieved by using abstract classes/interfaces.
Hiding information can be achieved by modifiers.

Example for Abstract method:
  abstract  void function();

Example of abstract class:
 abstract class TestAbstract{

   abstract void fun1();
   public void fun2(){
    statements
   }

abstract classes contain abstract methods and normal methods.

Abstract Class Example:
package com.oops;

abstract class Area{
int side;

Area(int a){
side=a;
}
abstract int area();
public void nonAbstractMethod(){
System.out.println("Non abstract Method");
}
}

class Square extends Area{

Square(int a) {
super(a);
}

@Override
int area() {

System.out.println("Square Area");
return side*side;
}

}

class Rect extends Area{

public Rect(int a) {
super(a);
// TODO Auto-generated constructor stub
}

@Override
int area() {
// TODO Auto-generated method stub
System.out.println("Area of Triangle");
return side*side;
}

}

public class AbstractClassExample {

public static void main(String args[]){

Square sq=new Square(3);
Rect rt=new Rect(5);

Area ar;

ar=sq;
System.out.println("Square Area"+ar.area());

ar=rt;
System.out.println("Rectangle area"+ar.area());
}
}

Output:
============
Square Area
Square Area9
Area of Triangle
Rectangle area25