Friday, July 19, 2013

Example for Abstraction


Shape.java

package com.core.Abstraction;

abstract class Shape
{
int height;
int width;
public static final int a=10;
abstract void draw();
abstract void print();
/**Defining a constructer, this method not needed to overidden.
 * A constructor cannot be final, static or abstract
 */
public Shape(){
}
}


Line.java


package com.core.Abstraction;

class Line extends Shape
{
@Override
        void draw()
        {
System.out.println("I am in Line");           
        }
Line(){
height = 5;
width = 5;
}
float lenght(){
return height*width;
}
@Override
void print() {
// TODO Auto-generated method stub
}
}


Curve.java


package com.core.Abstraction;

public class Curve extends Shape
{
@Override
        void draw()
        {
       System.out.println("I am in Curve");         
        }
Curve(){
height = 10;
width = 10;
}
float lenght(){
return height*width;
}
@Override
void print() {
// TODO Auto-generated method stub
}
}


TestAbstraction.java


package com.core.Abstraction;

public class TestAbstraction
{
public static void main( String[] args )
{
Shape lineShape = new Line();
System.out.println("Calling Line");
lineShape.draw();
Shape curveShape = new Curve();
System.out.println("Calling Curve");
curveShape.draw();
//in order to use the length method we have to create an instance for Line/Curve class
Line line = new Line();
System.out.println("Line Length is : "+line.lenght());
Curve curve = new Curve();
System.out.println("Line Length is : "+curve.lenght());
}
}


OutPut:


Calling Line
I am in Line
Calling Curve
I am in Curve
Line Length is : 25.0
Line Length is : 100.0