我正在慢慢地从C ++过渡到Java,但我不理解以下代码:
public class TestThread
{
public static void main (String [] args)
{
Thread t = new MyThreads()
{
public void run()
{
System.out.println(" foo");
}
};
t.start();
System.out.println("out of run");
}
}
对象类型“ MyThreads”正在实例化,但是“无效运行”功能是什么意思?
为什么在对象实例化后立即使用该语法编写?
该功能是否被覆盖?
什么时候需要/需要这种语法(使用对象实例化定义函数的语法)?在哪里首选/有用?
最佳答案
这意味着类MyThreads
要么要求您首先编写一个名称为run的方法,要么您的行为提供了在声明的位置更改现有run方法行为的能力。
这就像覆盖运行方法是否已经存在,还是要创建对象时创建方法一样。
这提供了创建MyThreads
对象的能力,而不必更改原始类或创建多个类。
public class TestThread
{
public static void main (String [] args)
{
Thread t = new MyThreads()
{
public void run()
{
System.out.println(" foo");
}
};
t.start();
Thread t1 = new MyThreads()
{
public void run()
{
System.out.println(" this time it is somethidn else");
}
};
t1.start();
System.out.println("out of run");
}
}
只需稍加修改即可显示具有此功能的优势。如果您观察到t1的运行方法所做的事情与t中的有所不同。因此,它现在是一个全新的线程。
关于java - 在Java中使用对象实例化定义方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27308481/