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
150 views
in Technique[技术] by (71.8m points)

java - Difference between new Test() and new Test() { }

What is the difference between these two ways of instantiating new objects of a class as follows:

Test t1=new Test();
Test t2=new Test(){ };

When I tried the following code, I could see that both objects could access the method foo(), but t2 cannot access the variable x (variable x cannot be resolved):

public class Test
{ 
    int x=0;
    public void foo(){ }

    public static void main (String args[])
    {
        Test t1=new Test();
        Test t2=new Test(){ };
        t1.x=10;
        t2.x=20;
        t1.foo();
        t2.foo();
        System.out.println(t1.x+" "t2.x);
    }
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Test t2=new Test(); will create the object of Test class.

But Test t2=new Test(){ }; will create a object of subclass of test (i.e. anonymous inner class in this case).

you can provide implementation for any method over there like

Test t2=new Test(){ 
public void foo(){ System.out.println("This is foo");}
};

so that when foo() method called from object t2 it will print This is foo.

Addition

Compile time error in your code is due to missing concatination operator

System.out.println(t1.x+" "+t2.x);
                          ###

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

2.1m questions

2.1m answers

60 comments

57.0k users

...