'When calling a getMethod on a Subclass object with the same var name as parent class which variable does it return?
You have two classes A and B:
public class Main {
public static void main(String[] args) {
// write your code here
B objB = new B();
objB.doSomething();
// Output: Im in class B
//10
}
}
class A{
private int num= 10;
public int getNum(){
return num;
}
}
class B extends A{
private int num= 5;
public void doSomething(){
System.out.println("Im in class B");
System.out.println(getNum());
}
}
What happends in memory and why is it printing the int 10 instead of 5 ? I understand that the objB has both the class A num, aswell as Class B num. But why if B inherits method getNum from A.
Shouldn't the return, return the value of num of class B ? as it is called upon the object created from class B ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
