Credits

Tuesday, July 20, 2010

More of Inheritance Illustration

 To define clearly the use of inheritance,  we apply this to a relationship between a student who has to go through different schooling levels including college.

The program below assigns the Student as the parent class while College as the child class. Through inheritance, the child class can simply call the methods and fields in the parent class by any object that instantiates it.

The program below illustrates this point.

[+/-] show/hide



import javax.swing.*;
public class SampleInheritance3{


public static void main (String args[]){
String myname=JOptionPane.showInputDialog("Input a student name: ");
String myaddress=JOptionPane.showInputDialog("Input a student's address: ");

Student1 obj1=new Student1();
obj1.setname(myname);
obj1.setaddress(myaddress);

System.out.println("object of parent class");
System.out.println("Student's name : "+obj1.getname());
System.out.println("Student's address : "+obj1.getaddress());

College1 obj2=new College1();
String mycourse=JOptionPane.showInputDialog("Input a student's college course: ");
obj2.setname(myname);
obj2.setaddress(myaddress);
obj2.setcourse(mycourse);

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

}

}


class Student1{
protected String name;
protected String address;



void setname(String xname)
{name=xname;}

String getname()
{return name;}

void setaddress(String xaddress)
{address=xaddress;}

String getaddress()
{return address;}

}



class College1 extends Student1{


String course;

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

String getcourse()
{return course;}

}












AddThis