Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Write a Constructor

This video was last updated on Jun 28 2022

Learn about constructors and how to define constructors in classes. Then, you’ll call them to create objects.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

So far, we’ve been creating objects and then setting up values after the fact. This can lead to cases where you might operate on an object before setting it. Now you can promise yourself to be vigilant, but you’re just setting yourself up for an error. Thankfully, we can use a constructor.

class User {
  int id = 0;
  String name = '';
}
var user = User()
..name = 'Ray'
..id = 42;
User(int id, String name) {
    this.id = id;
    this.name = name;
}
User(int id, String name) {
    id = id;
    name = name;
}
var user = User(42, 'ray');
print(user.id);
User(int id, String name) {
    this.id = id;
    this.name = name;
}
User(this.id, this.name);
User(this.id, this.name) { 
    print('this space for rent');
}
var user2 = User();
class User {
  final int id;
  final String name;
  
  User(this.id, this.name);
  
}

Reviews

Comments