+ 1

static method in java

Why can we access static method of same name in both parent class and base class by using name of class? Eg: class_name.method(); //method is static and common to base and derived class

13th Jun 2018, 12:00 AM
harshit
harshit - avatar
1 Réponse
+ 1
Static is an attribute that sets a method or a variable be accessed by the name of the class and not by an instance of it. Static methods/variables cannot interact with non-static methods/variables. If they are public, everyone can access them regardless of possible variables with the same name as it differs with the NAME_OF_CLASS.NAME_OF_VARIABLE (same with methods). Now let's look at the inheritance and overriding part. When you inherit a class, all public/protected methods are inherited with it, which means you can access them. When overriding, you just create another method with the same name as the inherited method, but with higher priority. Which means that by default, when calling a method with this name, it will by default call the overriding method, but overriding does not delete the overrided method. Let's take as an example class called A, A inherits from Object by default, so it inherits toString with it as well. toString of Object is returning the String to print everytime we use an instance of a class as a String. (For example, System.out.println) If we override this method because we don't like Java's toString, we can still access that toString. TL;DR / Summary Now let's move to a static inherit, just as above we can call the Static method/variable if we can access it. When inherited it will be defaultly used unless we override it. When we override it, the original method does not disappear and we can still access and call it, but the default method will be the overriding one. *All static variable/method references apply to both variable and method even if only one of those appear.
13th Jun 2018, 3:58 AM
Eldar Bakerman