Sunday, 19 August 2012

Abstract Class In Java


Introduction of Java Abstract Class


Facts for abstract class
  1. Its possible to create a refrence varible of an abstract class. Howerver its not possible to create an object of abstract class.
  2. The object of sub class = object of super class + some new features.
  3. Because of above fact, its possible to store the reference of sub class object into the reference variable of super class.
  4. Although, its possible to have a reference variable of super class, and in it we can store the reference of an object of sub class. However, through such a reference varible(reference is of super class and object is of sub class), we can access only those members of the sub class which the sub class had aquired or inherited from the super class. The new features (new data members, methods) that have been added to the sub class can't be access by the super class reference varible.
Save This file AbstractDemo.java

abstract class CShape
{
	private String shapeName;
	
	CShape(){shapeName = "Undefined";}
	CShape(String shapeName){this.shapeName = shapeName;}
	
	abstract float getArea();
	abstract float getPerimeter();
	abstract void inputDimensions();
	
	void show()
	{
		System.out.println("Shape : " + shapeName);
	}
}
import java.io.*;
class CRectangle extends CShape
{
	private int length;
	private int breadth;
	
	CRectangle()
	{
		super("Rectagle");
	}
	
	void inputDimensions()
	{
		Console console = System.console();
		System.out.print("Enter length : ");
		length = Integer.parseInt(console.readLine());
		System.out.print("Enter breadth : ");
		breadth = Integer.parseInt(console.readLine());	
	}
	
	
	float getArea(){return length * breadth;}
	float getPerimeter(){return 2 * (length + breadth);}
	
	void show()
	{
		super.show();
		System.out.println("Length  : " + length);
		System.out.println("Breadth : " + breadth);
		System.out.println();
	}
	
}
import java.io.*;
class CCircle extends CShape
{
	private float radius;
	private static float pi;
	
	static{pi = 22/7.0f;}
	
	CCircle()
	{
		super("Circle");
		radius = 0;
	}
	
	void inputDimensions()
	{
		Console console = System.console();
		System.out.print("Enter radius : ");
		radius = Float.parseFloat(console.readLine());
	}
	
	float getArea()
	{
		return pi * radius * radius;
	}
	
	float getPerimeter()
	{
		return 2 * pi * radius;
	}
	
	void show()
	{
		super.show();
		System.out.println("Radius : " + radius);
		System.out.println();
	}
	
}
public class AbstractDemo
{
	public static void main(String args[])
	{
		CShape shape;
		CRectangle rect  = new CRectangle();
		CCircle circle = new CCircle();
		
		
		
		shape = circle;
		shape = rect;
		
		shape.inputDimensions();
		shape.show();
		
	}
}

No comments:

Post a Comment