Credits

Thursday, July 22, 2010

 Method overriding is also possible in inheritance; with similar method name, a child class can replace the methods in the parent class.

Depending on which method you access, you will see unique actions from the instantiated class. See a sample program of how I have two methods of the same name.  And, with a constructor, I pass the initial value to my classes.

[+/-] show/hide



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

public static void main (String args[]){

ParentClass myObject1 = new ParentClass("Yuri");
myObject1.printGreetings();
BaseClass myObject2 = new BaseClass("Juana");
myObject2.printGreetings();

}

}


class ParentClass{
String name;

ParentClass(String xname)
{
name=xname;
}

void printGreetings()
{
JOptionPane.showMessageDialog(null,"Hello "+name);
}


}




class BaseClass extends ParentClass{
String xname;
BaseClass(String myname)
{
super(myname);
xname=myname;

}

void printGreetings()
{
JOptionPane.showMessageDialog(null,"Hi "+xname);

}



}












AddThis