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

Categories

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

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

1 Answer

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);
                          ###

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...