aspose file tools*
The moose likes Java in General and the fly likes strange behavior in inheritence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "strange behavior in inheritence " Watch "strange behavior in inheritence " New topic
Author

strange behavior in inheritence

Soumya Padhiary
Greenhorn

Joined: Jan 10, 2013
Posts: 20

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

Joined: Nov 04, 2009
Posts: 144

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.


SCJP, SCWCD, SCJD
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 2413
    
  50
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();
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: strange behavior in inheritence