Monday, August 29, 2011

Single Inheritance Example

//One parent class (super class) and one child class (sub class)

//SuperClass.java
public class SuperClass
{
float length,width;
SuparClass(float l,float w)
{
length = l;
width = w;
}
float area()
{
return length*width;
}
}

//SubClass.java
public class SubClass extends SuparClass
{

float hight;

SubClass(float l,float w,float h)
{
super(l,w); //super() must be the first statement in sub class. Other wise it shows error.
hight = h;
}
float volume()
{
return length*width*hight;
}
}

//MainClass.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainClass
{
public static void main(String args[]) throws IOException
{

float length,width,hight;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter length: ");
length = Float.valueOf(br.readLine()).floatValue();

System.out.print("Enter width: ");
width = Float.valueOf(br.readLine()).floatValue();

System.out.print("Enter higth: ");
hight = Float.valueOf(br.readLine()).floatValue();

SubClass sub = new SubClass(length, width, hight);
float area = sub.area();
float volme = sub.volume();

System.out.println("Area = "+area+" unit^2");
System.out.println("Volume = "+volme+" unit^3");
}
}


Output=>
Enter length: 20
Enter width: 10
Enter higth: 5
Area = 200.0 unit^2
Volume = 1000.0 unit^3


No comments:

Post a Comment