Java2all.com  

Abstract Classes





Share This Topic -

Abstract Classes in java:

When the keyword abstract appears in a class definition, it means that zero or more of it’s methods are abstract.

An abstract method has no body.

Some of the subclass has to override it and provide the implementation.

Objects cannot be created out of abstract class.

Abstract classes basically provide a guideline for the properties and methods of an object.

In order to use abstract classes, they have to be subclassed.

There are situations in which you want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method.

That is, sometimes you want to create a superclass that only defines generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.

One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method.

Syntax :

            abstract type name(parameter-list);

As you can see, no method body is present.

Any class that contains one or more abstract methods must also be declared abstract.

To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration.

There can be no objects of an abstract class.

That is, an abstract class cannot be directly instantiated with the new operator.

Any subclass of an abstract class must either implement all of the abstract methods of the superclass, or be itself declared abstract.

EX :

abstract class A1
{
	abstract void displayb1();
	void displaya1()
	{
		System.out.println("This is a concrete method");
	}
	
}

class B1 extends A1
{
	void displayb1()
	{
		System.out.println("B1's implementation");
	}
}

public class Abstract_Demo 
{
	public static void main(String args[])
	{
		B1 b = new B1();
		b.displayb1();
		b.displaya1();  
	}
}

 
Output :
 
B1's implementation
This is a concrete method
 
EX 2 :
 
 

 

 abstract class shape
{
	double dim1;
	double dim2;
	shape(double a, double b)
	{
		dim1 = a;
		dim2 = b;
	}
	abstract double area();
}

class rectangle extends shape
{
	rectangle(double a, double b)
	{
		super(a,b);
	}
	double area()
	{
		System.out.println("Area of rectangle.");
		return dim1*dim2;
	}
}

class triangle extends shape
{
	triangle(double a, double b)
	{
		super(a,b);
	}
	double area()
	{
		System.out.println("Area of triangle.");
		return dim1*dim2/2;
	}
}

public class Abstract_D2 
{
	public static void main(String args[])
	{
		rectangle r = new rectangle(10,20);
		triangle t = new triangle(10,6);
		
		System.out.println(r.area());
		System.out.println(t.area());	
	}
}

 
Output:
 
Area of rectangle.
200.0
Area of triangle.
30.0