Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static/Instance methods in Inheritance

 
Vegad Arvind
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
public class A {
public static void main (String args []) {
sup sup = new sub();
sup.staticmethod();
sup.instancemethod();
}
}
class sup {
static void staticmethod() {
System.out.println("sup's Static methods...");
}
void instancemethod() {
System.out.println("sup's instance methods...");
}
}
class sub extends sup {
static void staticmethod() {
System.out.println("sub's Static methods...");
}
void instancemethod() {
System.out.println("sub's instance methods...");
}
}

Prints Super's static methods
Prints Sub's instance methods
why staic method is execute from super class and instance from sub ?
how i can excute sub's static method from super sup = new sub()
can anybody explain me.

Avi
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Either put the Sub in a Sub type variable which will cause the static method of Sub to be called.
OR....... better yet, make the call to the static method using the class syntax instead of referencing an instance of the class.
Of course since you have "obsured" the issue by naming a variable with the SAME NAME as a class (really lousy idea) you have made it impossible. Rename the variable to mySup and then sup.staticmethod() will understand that "sup" means the class not the variable.

6.3.2 Obscured Declarations
A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type or a package. In these situations, the rules of �6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.
Obscuring is distinct from shadowing (�6.3.1) and hiding (�8.3, �8.4.6.2, �8.5, �9.3, �9.5). The naming conventions of �6.8 help reduce obscuring.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic