代码之家  ›  专栏  ›  技术社区  ›  Xcoder

如何在实例化时重写Dart方法[[副本]

  •  0
  • Xcoder  · 技术社区  · 4 年前

    在Java中,可以执行以下操作:

    class Example {
        void methodA(int x) {}
    }
    

    Example obj = new Example() {
        @Override
        void methodA(int x) {
            //some implementation here
        }
    }
    

    有没有办法重写Dart中对象实例化的方法?

    1 回复  |  直到 4 年前
        1
  •  0
  •   Md Omor Faruqe    4 年前

    //Dart程序来说明 //方法重写概念

    class SuperGeek {
        
      // Creating a method
      void show(){
        print("This is class SuperGeek.");
      }
    }
       
    class SubGeek extends SuperGeek {
        
      // Overriding show method
      void show(){
        print("This is class SubGeek child of SuperGeek.");
      }
    }
       
    void main() {
      // Creating objects
      //of both the classes
      SuperGeek geek1 = new SuperGeek();
      SubGeek geek2 = new SubGeek();
        
      // Calling same function
      // from both the classes
      // object to show method overriding
      geek1.show();
      geek2.show();
    }
    

    这是超级怪才。

    第二个例子:

    //Dart程序来说明 //方法重写概念

    class SuperGeek {
        
      // Creating a method
      void show(){
        print("This is class SuperGeek.");
      }
    }
       
    class SubGeek1 extends SuperGeek {
        
      // Overriding show method
      void show(){
        print("This is class SubGeek1 child of SuperGeek.");
      }
    }
       
    class SubGeek2 extends SuperGeek {
      // Overriding show method
       
      void show(){
        print("This is class SubGeek2 child of SuperGeek.");
      }
    }
      
    void main() {
        
      // Creating objects of both the classes
      SuperGeek geek1 = new SuperGeek();
      SubGeek1 geek2 = new SubGeek1();
      SubGeek2 geek3 = new SubGeek2();
        
      // Calling same function
      // from both the classes
      // object to show method 
      // overriding
      geek1.show();
      geek2.show();
      geek3.show();
    }
    

    输出:

    这是超级怪人的一个孩子。 这是超级极客的2级孩子。

    详情请点击链接 https://www.geeksforgeeks.org/method-overriding-in-dart/