Home > Software engineering >  making an instance of a class in Dart
making an instance of a class in Dart

Time:11-18

i'm a beginner in Dart programming and i'm a bit confused when it comes to making an instance of a class, suppose we have a class named Student what is the difference between these two:

Student student;

and

Student student = new Student();

CodePudding user response:

In Student student; you are just declaring a field that you can later store a Student object in. You aren't creating an actual object here.

At Student student = new Student(); you are creating an Student object which is stored in student. You now have an instance of the Student class that you can use methods on by calling for example student.study().

In dart (as of Dart 2), unlike Java, you can also omit the "new" keyword.

Which means you can write like this instead: Student student = Student();

Example of using both your provided rows would look like this;

Student student; 
student = Student();

Which however can just be writted like this: Student student = Student();

  • Related