簡體   English   中英

在Java中使用對象實例化定義方法

[英]Define method with object instantiation in java

我正在慢慢地從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”對象類型,但是“無效運行”功能是什么意思?

為什么在對象實例化后立即使用該語法編寫?

該功能是否被覆蓋?

什么時候需要/需要這種語法(使用對象實例化定義函數的語法)? 在哪里首選/有用?

此代碼等效於

public class TestThread 
{
    static class MyThreadSubclass extends MyClass {
       public void run() {
         System.out.println("foo");
       }
    }
    public static void main (String [] args) 
    {
        Thread t = new MyThreadSubclass();
        t.start();
        System.out.println("out of run");
    }
}

這只是定義子類內聯的一種簡便方法,而不必給它命名。 它只是語法糖。 它正在創建一個子類的對象,該對象將覆蓋MyThreads run()方法。

這意味着類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中的方法有所不同。 因此,它現在是全新的線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM