Free CoreJava Programs Source codes | Examples | Video Tutorials Download

Tuesday, January 27, 2009

Demonstration of A Class Inheritance Heirarchy

/**

* Write a program which demonstrates a class inheritance heirarchy. class M

* extends java.lan.Object and has 2 instance varaibles of type float and

* String. class N extends M and has one instance variable of type double.

* Instantiate class N and display its variables.

*

* @author Ritesh

*

*/

public class Inher1 {

/**

* execution begin from here

*

* @param args

*/

public static void main(String[] args) {

// creating object of N class and display it

System.out.println("Display Values Of Member Variables : ");

new N(1.1f, "Ram", 1.1).display();

}

}

/**

* Class M which is parent of Class N

* @author Ritesh

*

*/

class M {

// member variable

private float flVar;

// member variable

private String strObj;

/**

* constructor to initialize variables

*

* @param flNo

* float input value

* @param strTemp

* string input value

*/

M(float flNo, String strTemp) {

flVar = flNo;

strObj = strTemp;

}

/**

* get value of flVar

*

* @return flVar

*/

public float getFlVar() {

return flVar;

}

/**

* sets value of flvar

*

* @param flVar

* input

*/

public void setFlVar(float flVar) {

this.flVar = flVar;

}

/**

* get value of strObj

*

* @return strObj

*/

public String getStrObj() {

return strObj;

}

/**

* set value of strTemp

*

* @param strTemp

* input to strObj

*/

public void setStrObj(String strTemp) {

this.strObj = strTemp;

}

}

/**

* It extends M with new variable and methods

* @author Ritesh

*

*/

class N extends M {

// member variable of type double

private double dbVar;

/**

* constructor that initialize the super constructor also

*

* @param flVar

* float input

* @param strObj

* string input

* @param dbVar

* double input

*/

N(float flVar, String strObj, double dbVar) {

// calls the super class constructor

super(flVar, strObj);

// set the dbVar

setDbVar(dbVar);

}

/**

* display all the variables of child and parent class

*

*/

public void display() {

System.out.println("\tflVar : " + getFlVar());

System.out.println("\tstrObj : " + getStrObj());

System.out.println("\tdbVar : " + getDbVar());

}

/**

* get dbVar value

*

* @return dbVar

*/

public double getDbVar() {

return dbVar;

}

/**

* set dbVar value

*

* @param dbVar

* input value

*/

public void setDbVar(double dbVar) {

this.dbVar = dbVar;

}

}

No comments:

Post a Comment

Followers