繁体   English   中英

在java中用块创建构造函数

[英]Create constructor with block in java

在Android中,有一个名为Runnable的类,要获取它的实例,代码如下:

Runnable r = new Runnable() {
    @Override
    public void run() {
        //do whatever here
    }
}

我怎么能在我自己的课上做到这一点?

例如:

package com.tylerr147.constructorThingy;
public class Whatever {
    //do whatever for the cunstructor here
}

package com.tylerr147.constructorThingy;
public class OtherClass {
    Whatever w = new Whatever() {
        @Override
        public void WhateverRun() {
            //do something
        }
    }
}

任何帮助表示赞赏谢谢!

public interface Whatever {
    public void myMethod();
}

您可以声明要连接的Whatever类,并且可以新建并实现您的方法,例如:

Whatever w = new Whatever () {
   @Override
   public void myMethod() {
    ...
   }
}

Runnable只是一个必须覆盖的方法运行的接口

如果你想使用@override,你应该使用whatrun方法使你的Whatever成为一个接口。

public interface Whatever {
    public void WhateverRun();
}

   Whatever w = new Whatever () {
   @Override
   public void WhateverRun() {
    ...
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM