Inheriting Class in Dart Language Cannot Invoke Inheriting Function

Asked 1 years ago, Updated 1 years ago, 117 views

I write Class in Dart, but if I inherit it, I will not be able to call the inheritance source function.
How do I manage these situations?

Because the actual inheritance source has a long class name, I tried to make it accessible with a short class name, but when I inherited it, I couldn't call the original class.

Error Contents:

The method 'hogeFunc'isn't defined for the type 'hoge2'.
Try correcting the name to the name of an existing method, or defining a method named 

Current State Code:

class hoge2 extensions hoge{}

class hoge {

  static void hogeFunc(){

  }
}

dart

2022-09-30 19:18

1 Answers

Dart cannot invoke the superclass (base class) static (static) method from the subclass (derivative class) type symbol.

In addition, it is wrong to use inheritance for the purpose of creating a short model name.
In Dart 2.13 recently released, the typedef type alias for non-analogical type has been added as a new feature, so if you want to define a shortened name, you should use it.

class SuperClass {
  static void someMethod() {
    print("SuperClass.someMethod() called.");
  }
}

classSubClass extensions SuperClass {
}

typeef MyTypeAlias=SuperClass;

void main() {
  try{
    SuperClass.someMethod();
    MyTypeAlias.someMethod();

    // SubClass.someMethod(); // Wrong.
    // varobj1 = new SuperClass();
    //obj1.someMethod(); // Wrong.
    // varobj2 = new SubClass();
    //obj2.someMethod(); // Wrong.
  } catch(e, stackTrace){
    print(e);
    print(stackTrace);
  }
}

Java can invoke superclass static methods from subclass type symbols or static methods from instances, but these notation is deprecated.Most static analysis tools warn you when you call them this way.

class SuperClass {
    static void someMethod() {
        System.out.println("SuperClass.someMethod() called.");
    }
}

classSubClass extensions SuperClass {
}

public class Main {
    public static void main(String[]args) {
        SuperClass.someMethod();

        SubClass.someMethod();// Deprecated.
        varobj1 = new SuperClass();
        obj1.someMethod();// Deprecated.
        varobj2 = newSubClass();
        obj2.someMethod();// Deprecated.
    }
}

Incidentally, Dart's official style guide says that UpperCamelCase is the name of the type.This is the same as Java custom.

DO name types using UpperCamelCase.
Classes, enum types, typefs, and type parameters should capitalize the first letter of each word (including the first word), and use no separator.


2022-09-30 19:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.