Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

java - Is calling static methods via an object "bad form"? Why?

In a recent question, someone asked about static methods and one of the answers stated that you generally call them with something like:

MyClassName.myStaticMethod();

The comments on that also stated that you could also call it via an object with:

MyClassName myVar;
myVar.myStaticMethod();

but that it was considered bad form.

Now it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not (a).

Is there some problem with calling static functions via an object? Obviously you wouldn't want to create a brand new object just to call it:

Integer xyzzy;
int plugh = xyzzy.parseInt ("42", 10);

But, if you already have an object of the desired type, is there a problem in using it?


(a) Obviously, I can't call a non-static method with:

MyClassName.myNonStaticMethod();

but that's not the issue I'm asking about here.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In my opinion, the real use case that makes this so unreadable is something like this. What does the code below print?

//in a main method somewhere
Super instance = new Sub();
instance.method();

//...
public class Super {
    public static void method() {
        System.out.println("Super");
    }
}

public class Sub extends Super {
    public static void method() {
        System.out.println("Sub");
    }
}

The answer is that it prints "Super", because static methods are not virtual. Even though instance is-a Sub, the compiler can only go on the type of the variable which is Super. However, by calling the method via instance rather than Super, you are subtly implying that it will be virtual.

In fact, a developer reading the instance.method() would have to look at the declaration of the method (its signature) to know which method it actually being called. You mention

it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not

But in the case above context is actually very important!

I can fairly confidently say it was a mistake for the language designers to allow this in the first place. Stay away.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...