Using Constructors
Lesson 11 of 12 in Coddy's Basics of Classes and Objects in C# course.
When we create an object using the new keyword, we always execute a constructor method (what we learned in the class chapter). By default, every class in C# has an empty constructor, like below:
class MyClass {
public MyClass() {
}
}And when we use:
MyClass myObj = new MyClass();We actually execute this invisible constructor!
As we learned before, let's assume the class:
class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}Now we can create multiple objects using this constructor, like this:
Point p1 = new Point(5, 3);
Point p2 = new Point(1, 2);
Point p3 = new Point(0, 0);This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou are given a code with a class named Animal, in the main method:
- Create an object named
cowof type Animal, with type"cow"and voice“Moo” - Create an object named
dogof type Animal, with type"dog"and voice“Woof”
Try it yourself
using System;
class Animal {
public string type;
public string voice;
public Animal(string type, string voice) {
this.type = type;
this.voice = voice;
}
}
class Program {
public static void Main(string[] args) {
// Write code here
// Don't change below this line
Console.WriteLine(cow.type + " is making " + cow.voice);
Console.WriteLine(dog.type + " is making " + dog.voice);
}
}All lessons in Basics of Classes and Objects in C#
1Introduction
Introduction