Credits

Tuesday, July 20, 2010

The Use of Super in Java Programs

The Java keyword super has  a special use in the application of inheritance. When we pass parameters to our constructors, we also perform the same thing for parents and child classes. A child class may access the parent class' fields through the use of super to pass parameters to parent class.

See the sample below for the illustration.

[+/-] show/hide



/*with super in constructor*/
import javax.swing.*;
public class SampleInheritance4{


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


College2 obj1=new College2(myname,myaddress);
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 Student2{
protected String name;
protected String address;



String getname()
{return this.name;}

String getaddress()
{return this.address;}

}



class College2 extends Student2{

College2(String xname,String xaddress){
super.name=xname; // passing the values of xname and xaddress to parent variables names and address
super.address=xaddress;
}

String course;

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

String getcourse()
{return this.course;}

}












AddThis