new Test()和new Test(){}之间的区别

十字军

这两种实例化类的新对象的方式之间有什么区别,如下所示:

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

当我尝试以下代码时,我可以看到两个对象都可以访问方法foo(),但是t2无法访问variable xvariable x无法解析):

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);
    }
}
eatSleepCode:

Test t2=new Test(); 将创建Test类的对象。

但是Test t2=new Test(){ };将创建一个测试子类的对象(在这种情况下,即匿名内部类)。

您可以在那提供任何方法的实现

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

这样,当foo()从对象调用方法t2,它将打印出来This is foo

加成

代码中的编译时错误是由于缺少条件运算符

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

=和new之间的区别

GetObject和New之间的区别

“ new”和“ gen”之间的区别

new Class(){...}和new Class {...}之间的区别

new Function()和new Function()()之间的区别

new List(){...}和new List {...}之间的区别

调用new和getInstance()之间的区别

new [0]和null之间的区别-Java

int和new int()之间的区别

“ new”和“ =”之间关于指针的区别

参数“ new Foo()”和“&Foo()”之间的区别

int * a和int * a = new int之间的区别

./test.pl和perl test.pl之间的区别

`rails test <filename>` 和 `rails test` 之间的区别

Session(“ foo”)=“ test”和Cstr(Session(“ foo”)=“ test”之间的区别

“ ClassA对象= new ClassA();”之间的区别 和“ new ClassA();”?

new Class [] {}和new Class [0]之间有区别吗?

+ new Date()和1 * new Date()之间的区别

Java中new String [] {}和new String []之间的区别

Keras:test_on_batch和predict_on_batch之间的区别

Vue-Test-Utils的“ mount”和“ shallowMount”之间的区别?

getInt()和new Integer(getString())之间有什么区别?

了解Object.create()和new SomeFunction()之间的区别

Java:新Properties(...)和new Properties()。putAll(...)之间的区别

用rails在ruby中调用create和new()之间的区别

“ Hash.new(0)”和“ {}”之间有什么区别

(习惯用法?)new(T)和&T {...}之间的区别?

new()和“常规”分配之间有区别吗?

Rails的“ raise StandardError.new”和“ raise StandardError”之间的区别