You are on page 1of 5

Excercise1:

Derive two sub classes son and daughter from the above class and override the method Iam() in each of
the subclass and prints an appropriate message in each overridden method. You should also define a
suitable constructor for each of these sub classes. Now write a test class to check the functionality of
above example. In main() method create three objects one for each father, son and daughter
respectively and call their Iam() method non polymorphically. Then create an array of father references
of size ten and initialize this array randomly with the objects of daughter and son. Then traverse this
array and call the Iam() method polymorphically and display the results

Public class father

int age;

father(int x)

age=x;

public void Iam()

System.out.println(“I AM FATHER and My AGE = %d”, age);

Class son extends father{

// method overidding

Public void Iam(){

System.out.println(“ I AM SON and MY AGE =%d”,age);

Class daughter extends son{

Public void Iam(){

System.out.println(“ I AM DAUGHTER and MY AGE = %d”, age);

Lab8 task
Father f1 = new Father();

Son s1 = new Son();

Daughter d1 = new Duaghter();

Exercise 2:

ShapeHierarchy: Implement the Shape hierarchy shown in Fig. 1 givenbelow. Each


TwoDimensionalShape should contain method getArea to calculate the area of the two-dimensional
shape. Each ThreeDimensionalShape should have methods getArea and getVolume to calculate the
surface area and volume, respectively, of the three-dimensional shape. Create a program that uses an
array of Shape references to objects of each concrete class in the hierarchy. The program should print a
text description of the object to which each array element refers. Also, in the loop that processes all the
shapes in the array, determine whether each shape is a TwoDimensionalShape or a
ThreeDimensionalShape. If it’s a TwoDimensionalShape, display its area. If it’s a
ThreeDimensionalShape, display its area and volume.

package shapes;

public abstract class Shape {

private double dimOne;

private double dimTwo;

private double dimThree;

//1 arg constructor

public Shape (double dim1) {

dimOne = dim1;

Lab8 task
}

//2 arg constructor

public Shape (double dim1, double dim2) {

dimOne = dim1;

dimTwo = dim2;

//3 arg constructor

public Shape (double dim1, double dim2, double dim3){

dimOne = dim1;

dimTwo = dim2;

dimThree = dim3;

//Setters and getters:

//dim 1

public void setDimOne(double dim1) {

dimOne = dim1;

public double getDimOne() {

return dimOne;

Lab8 task
//dim2

public void setDimTwo(double dim2) {

dimTwo = dim2;

public double getDimTwo() {

return dimTwo;

//dim3

public void setDimThree(double dim3) {

dimThree = dim3;

public double getDimThree() {

return dimThree;

public abstract double getArea();

public String getName() {

return getClass().getName();

@Override

public String toString(){

Lab8 task
return "area = " + getArea();

Lab8 task

You might also like