What if a class extends another class and they each have a method with the same prototype? When to call the subclass and when to call superclass?
m confused with very simple example of Inheritance like.
class A
{
int k=1;
void show()
{
System.out.println("===inside A class= Show()=="+k);
}
}
class B extends A
{
int k=8;
void show()
{
System.out.println("===inside B class=Show()=="+k);
}
void show1()
{
System.out.println("===inside B class show1() ===");
}
}
public class Inheritance
{
public static void main(String s[])
{
A a=new B();
a.show();
//a.show1();//error
System.out.println("===="+a.k);
}
}
in the above example i m making reference of superclass to Subclass object. Now i have two Question.
1-Why we Do, means===> A a=new B(); Why not use B=new B(); or A a=New A();When We should do Like it A a=new B();
2-when i call a.show(); its print "==inside B class=Show()==" while it should show "==inside A class= Show()==" because as i know Reference Of A class know only A class member only.
because if i will a.show1(); it give Error Because show1() is function of class B. and if it show class B member also then i print a.k it show "1". why not "8" defined in Class B."
Re: inheritance problem with references
1) A a=new B()
With A a=new B() you can access overrided method show but not show1 method, this method is accessible only from class B instances and also your LOCAL (Class A) variable k
Inside B class method show() === 8
Inside class variable:1
2) B b=new B()
With B a=new B() you can access overrided class A method show, method show1 inside class B and your LOCAL (Class B) variable k
Inside B class method show() === 8
Inside B class method show1() === 8
Inside class variable:8
3) A c=new A()
With A c=new A() you can access method show inside Class A, and your LOCAL (Class A) variable k
Inside A class method Show() === 1
Inside class variable:1