• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strange behavior in inheritence

 
Soumya Padhiary
Greenhorn
Posts: 20
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A{
static void func1(){
System.out.println("inside static func of A");
}
int func(){
System.out.println("inside instance func of A");
return 3;
}
}

class B extends A{
static void func1(){
System.out.println("inside static func of B");
}
int func(){
System.out.println("inside instance func of B");
return 4;
}
public static void main(String[] arg)
{
B b=new B();
A a=b;
a.func1(); //output: inside static func of A
a.func(); //output: inside instance func of B
}
}

In the 1st output, the priority of execution of func should go to the func of submost object(i.e. B class); same as the second output . Any reason ??
 
Dennis Grimbergen
Ranch Hand
Posts: 159
IntelliJ IDE Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
func1() in class B is not overriding func1() in class A. The static method func1() in class B is redefined. A static method is not associated with an instance of a class, so such a method can't be overriden.
Because your reference type is A, func1() of class A will be invoked.
 
Tony Docherty
Bartender
Posts: 2971
59
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is generally considered bad practice to call static methods via an object variable, ie if you want to call the static func1() method in class A you use A.func1() and to call the static func1() method in class B you use B.func1();
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic