Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Static Methods/Variables in Java from an Instance

Can anyone explain to me why java allows you to access static methods and members from an instance? A bad example, if I have a class called RedShape and it has a static method called getColor() which returns "red", why does java allow you to call the static method from an instance of RedShape? To me this seems to violate some of the core concepts of OO language design. At the least, it should come with a compiler warning.

Thanks in advance.

Edit:

In particular, I'm asking about when you have something like

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

where getColor is a static method of the RedShape class. This doesn't make any sense that it's allowed and doesn't give a compiler warning on the command line via javac. I see that it's "strongly discouraged", but was curious if there was a technical or reasonable reason behind why it's allowed outside of "because C++ allows it."

like image 489
Brian Hasden Avatar asked Dec 18 '22 05:12

Brian Hasden


2 Answers

I don't see anything wrong with calling a static method from an instance. What's wrong with that? In particular, quite often there are methods which are useful within the logic of a class, but which don't actually need to manipulate the instance itself.

I do object to calling a static method via an instance reference. Classic example:

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

This comes with a compiler warning in some IDEs - certainly in Eclipse, assuming you turn it on. (Java / Compiler / Errors and Warnings / Code Style / Non-static access to static member.) Personally I consider that a mistake in the design of Java. (It's one of the mistakes that C# managed to avoid copying.)

like image 138
Jon Skeet Avatar answered Jan 14 '23 04:01

Jon Skeet


There's really no reason why you can actually do this.

My only guess was that it would allow you to override static methods, but you can't.

If you try the following scenario:

Banana has a static method called 'test' (this prints 'banana') Apple extends Banana and "overrides" the static method called 'test' (this prints 'apple')

and you do something like this:

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

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

The resulting output is:

apple
banana
banana

So effectively, it's pretty useless.

like image 33
Malaxeur Avatar answered Jan 14 '23 03:01

Malaxeur