Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

Super simple but hard question for a Dart beginner

I am trying to learn Dart language. Following code seems very straight forward but does not work. I know it may be a foolish question for an expert but for me hard to understand why not ?

class Car{

  carFun(){
  
    print("Test");

  }
  
}

main(){

  Car.carFun();

}

question from:https://stackoverflow.com/questions/65909810/super-simple-but-hard-question-for-a-dart-beginner

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Already answered but I'll give more context.

You need to mark your method as static:

static carFun(){ ...

This makes the method available as a 'Class Method'; right now, as you have defined it, it is an 'Object Method'. This means that you need to make an object out of the class Car to be able to use it, which would be something like this:

var myCar = new Car();
myCar.carFun();

This way you instantiated an object and used a defined method for it. Marking it as static would make this approach not work. This is one of the many differences between a Class and an Object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...