Wednesday, December 8, 2010

Java's Use of super ( ) on Inheritance

When we instantiate, we activate our constructors, but if  we want to pass new values as arguments, then, we embed these arguments in our instantiation command as follows:

College2 obj1=new College2(myname,myaddress);

But, when we establish parent - child relationship, constructors are not inherited by the child class. A child class can only have access  to member fields and methods of the parent class. To remedy this, super ( ) command is used. Use super ( ) without the arguments to activate the default constructor values of the parent class just like the program below.

However, if you wish to enforce your new values for your parent constructor, then, embed in super ( ) some arguments such as below:


[+/-] show/hide

* @author Rose
import javax.swing.*;

public class SampleInheritance4a {

/*with super in constructor*/

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);

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



class Student2{
protected String name="JUan";
protected String address="Lagao";

Student2(String yname,String yaddress){




String getname()

String getaddress()
{return this.address;}


class College2 extends Student2{

College2(String xname,String xaddress){


String course;

void setcourse(String xcourse)

String getcourse()
{return this.course;}