Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - What is calling class method on constructor?

I'm aware of just basic concepts of java. Today I was learning about super keyword from here

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.11.2

And in code example found this code snippet

class Test {
    public static void main(String[] args) {
        new T3().test(); ---> What is happening here ?
    }
}

May I know what is happening with new T3().test(); ? Is it a new object ? If yest then why its not written as below ?

T3 ob = new T3().test();

Or they have written in way because return type of test() method is void. Means no reference type can be created ? Am I correct ?

Can anyone help me to understand this ? What is actually happening with this code snippet ? I just know only we use this way only when we need to create an object like this only

Classtype vrblName = new Constructor();

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your expression parses as (new T3()).test(), not new (T3().test()) as if it were destined to create a new object. Therefore, as mentioned in comments, it creates a T3 object, invokes the test() method on it, and discards the result. (The T3 object may or may not survive this processs, since it could publish pointers to itself in its constructor or in test().) It's no different from writing

static T3 findSomeT3() { /* could return a new one or an existing one */ }
public static void main(String[] args) {
  findSomeT3().test();
}

which also might or might not discard a T3 object upon completion.

Note, by the way, that the name after new should not be considered a constructor; it's a class name. A constructor is invoked to initialize it, of course, and the constructor is declared by treating the class's name as a function name, but it's still the class you're talking about.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...