Hi, Please have a look at this code:
SCANARIO 1:
public class A {
public int num=500;
public int getNum() {return num;}
public static void main(String args[]) {
A myA= new A();
System.out.println(myA.getNum());
B myB= new B();
System.out.println(myB.getNum());
A myC= new B();
myC.num=7777;
System.out.println(myC.getNum());
}
}
class B extends A {
public int num=8800;
private void print() {
System.out.println("sub class print message");
}
}
OUTPUT:
500
500
7777
first output is fine. What about instance of B class??? Rather then printing 8800, inherited value of 500 is printed. Is it because getNum() is only defined in supper class A?? But class B would also inherit getNum()... so should it not print 8800 on second line using the inherited getNum(). 3rd output again print inherited value of 7777 rather then 8800.
SCNARIO 2:
Copy getNum() method from superclass and paste it in class B. Now
OUTPUT:
500
8800
8800
Now since we have getNum in class B. It prints 8800 and ignore inherited values of num. I am confused because class B inherited getNum anyway so why do we need to write it explicitly in class B??
Please HELP!!!
[ September 11, 2007: Message edited by: Nomi Malik ]
SCANARIO 1:
public class A {
public int num=500;
public int getNum() {return num;}
public static void main(String args[]) {
A myA= new A();
System.out.println(myA.getNum());
B myB= new B();
System.out.println(myB.getNum());
A myC= new B();
myC.num=7777;
System.out.println(myC.getNum());
}
}
class B extends A {
public int num=8800;
private void print() {
System.out.println("sub class print message");
}
}
OUTPUT:
500
500
7777
first output is fine. What about instance of B class??? Rather then printing 8800, inherited value of 500 is printed. Is it because getNum() is only defined in supper class A?? But class B would also inherit getNum()... so should it not print 8800 on second line using the inherited getNum(). 3rd output again print inherited value of 7777 rather then 8800.
SCNARIO 2:
Copy getNum() method from superclass and paste it in class B. Now
OUTPUT:
500
8800
8800
Now since we have getNum in class B. It prints 8800 and ignore inherited values of num. I am confused because class B inherited getNum anyway so why do we need to write it explicitly in class B??
Please HELP!!!
[ September 11, 2007: Message edited by: Nomi Malik ]