Credits

Thursday, December 9, 2010

Java's More Use of Inheritance

 As discussed in my older posts, inheritance allows us to re-use codes as we establish parent and child relationship. With this, the child class(es) can explicitly have access to member fields and methods in a parent class while the child execute its own distinct methods.

I have declared my variables to be static and with this, they can be accessed using the class name written as such:

super(SampleInheritance5.myname,SampleInheritance5.myaddress);
 To see the entire program with the use of static variables in a parent - child classes, simply check the see more (+/-) signs.
[+/-] show/hide


/*with super in constructor*/
import javax.swing.*;
public class SampleInheritance5{
static String myname;
static String myaddress;

public static void main (String args[]){
String xmyname = JOptionPane.showInputDialog("Input a student name: ");
String xmyaddress = JOptionPane.showInputDialog("Input a student's address: ");
String mycourse=JOptionPane.showInputDialog("Input a student's college course: ");

myname=xmyname;
myaddress=xmyaddress;

College3 obj1=new College3();
obj1.setcourse(mycourse);

JOptionPane.showMessageDialog(null,"object of the child class");
JOptionPane.showMessageDialog(null,"Student's Info: "+"\n"+obj1.name+"\n"+obj1.getaddress()+"\n"+obj1.getcourse());

}

}


class Student3{
protected String name;
protected String address;

Student3(String xname, String xaddress){
name=xname;
address=xaddress;
}


String getname()
{return this.name;}

String getaddress()
{return this.address;}

}



class College3 extends Student3{

College3(){
super(SampleInheritance5.myname,SampleInheritance5.myaddress);
}

String course;

void setcourse(String xcourse)
{course=xcourse;}

String getcourse()
{return this.course;}

}












AddThis