Reference static methods / variables in Java from an instance

Can someone explain to me why java allows you to access static methods and members from an instance? Bad example, if I have an object called RedShape and it has a static method called getColor () that returns “red”, why does Java allow you to call a static method from an instance of RedShape? For me, this seems to violate some of the basic concepts of OO language design. At least it should appear with a compiler warning.

Thanks in advance.

Edit:

In particular, I ask when you have something like

RedShape test = new RedShape();
test.getColor();

where getColor is a static method of the RedShape class. It makes no sense that it is allowed and does not give a compiler warning on the command line via javac. I see that it was “very discouraged,” but it was curious if there was a technical or reasonable reason why it was allowed outside “because C ++ allows it”.

+4
source share
5 answers

There really is no reason why you can really do this.

My only assumption was that this would allow you to override static methods, but you cannot .

If you try the following scenario:

, "" ( "" ) Apple "" "" ( "" )

- :

public static void main(String[] args) {
    Apple apple = new Apple();
    Banana banana = new Banana();
    Banana base = new Apple();

    apple.test();
    banana.test();
    base.test();
}

:

apple
banana
banana

, .

+3

. ? , , , .

. :

Thread thread = new Thread(...);
thread.sleep(5000); // Doesn't do what it looks like

IDE - , Eclipse, . (Java/Compiler/Errors and Warnings/Code Style/ .) , Java. ( , # .)

+9

.

, OO.

0

, ++, , 20/20 , .

, , this., ( ), . , this. ( , ).

, , .

0
public class MyClass {
    public static String myString;
}


public class AnotherClass {
   public void doSomething() {
       doAnotherThing();
   }
   public static doAnotherThing() {
       MyClass.myString = "something";
   }

Here we refer to a static variable from a non-static method (indirectly) by invoking a static method from a non-static method.

0
source

All Articles