Reputation: 534
I need help with this Java Program example. This example is from the book Java: Seventh Edition by Herbert Schildt.
I have few doubts about this program and also doubts about the text(explanation of this topic) written in this book. This program is written under Inheritance --> Method Overriding. Here A is the super class of B and B is the super class of C. In this program callme() is a method written in the three classes where each callme() overides another callme() method.
1) In the program below, what does obtain a reference of type A means? (This concept is implemented in the line A r; in the Main method)
2) What is name space convention?
3) In this program, what does "r referes to an A object mean"? (This concept is implemented in the lines r.callme(); written in the main method.)
class A
{
void callme()
{
System.out.println("Im in the class A");
}
}
class B extends A
{
void callme()
{
System.out.println("Im in the class B");
}
}
class C extends B
{
void callme()
{
System.out.println("Im in the class C");
}
}
public class Dispatch
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A r;
r = a;
r.callme();
r = b;
r.callme();
r = c;
r.callme();
}
}
Upvotes: 1
Views: 2952
Reputation: 26
This is a way to overcome the problem of method over-riding. If you want to get rid of method over-ridden at some time during your development then you can use this way of DMD.
Referring your example with comments:
class A //Super class A
{
void callme() // method callme() that'll be overwritten next in subclasses
{
System.out.println("Im in the class A");
}
}
class B extends A //Subclass B inherited from A
{
void callme() //method callme() of Super class A is over-hided here
{
System.out.println("Im in the class B");
}
}
class C extends B //Subclass C, inherited from B
{
void callme() // this time B subclass method callme() is over-hided
{
System.out.println("Im in the class C");
}
}
//Now suppose, during you development phase at some time, you don't want to use over-ridden methods, here is DMD to help you out at run time.
public class Dispatch
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A r;
// r is a reference to class A
// this reference should be assigned to each type of object and called at
// run time without compiling.
r = a;
r.callme();
r = b; r.callme();
r = c; r.callme();
}
}
Upvotes: 1