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
Joined: Sep 29, 2000
Posts: 8521
posted
0
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.
"JavaRanch, where the deer and the Certified play" - David O'Meara
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.