0

I extended a class(A) from a class(B) that has a static method then in other class(C) im creating an instance of class(A) and Im able to access static method of class B why is it happening?

Class A:

public class NetworkUtils extends AbsClass {}

Class B:

public class AbsClass {
static public void eat(){}
}

In Class C:

Networkutills network = new Networkutills();
network.eat();    //why should I access eat class method
blackHawk
  • 6,047
  • 13
  • 57
  • 100
  • 1
    Why do you believe you *shouldn't* be able to do this? – Oliver Charlesworth Apr 30 '17 at 16:50
  • the static method is **public** : any class can invoke this method. see also: http://stackoverflow.com/questions/10459487 – Pierre Apr 30 '17 at 16:51
  • Please, look at this answer: http://stackoverflow.com/a/10292034/4563745 – Vasiliy Vlasov Apr 30 '17 at 16:51
  • It is because you are extending NetworkUtils to AbsClass it means that NetworkUtils will inherit all the properties of AbsClass so its obvious that you can access all the methods of AbsClass by creating an instance for NetworkUtils – karthik vishnu kumar Apr 30 '17 at 16:56
  • It is worth noting that while your code compiles, you shouldn't be using reference variables to access static content. Use class name instead to avoid confusion. – Pshemo Apr 30 '17 at 16:58
  • okay its inherited, but static members are accessible through class name not by instance, then why its accessible by instance when extended – blackHawk Apr 30 '17 at 16:59
  • 1
    "but static members are accessible through class name not by instance" true, but unfortunately Java allows `instance.staticMethod()` because at compilation time such code will be changed to `ClassOfInstance.staticMethod()`. Many think that allowing this syntax was bad design decision since instead of being helpful, mostly confuses people new to Java who start to think that staticMethod can be invoked on `instance` itself (which is not true). So `network.eat();` will be compiled into `Networkutills.eat()` and this code is correct because of reasons explained in duplicate. – Pshemo Apr 30 '17 at 18:53

1 Answers1

0

Because Class A inherits Class B.

Maybe you are interessted in this.

Community
  • 1
  • 1
Benjamin J.
  • 1,239
  • 1
  • 15
  • 28