Using Constructors
Lesson 11 of 12 in Coddy's Basics of Classes and Objects in Java 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 Java 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
class Animal {
String type;
String voice;
public Animal(String type, String voice) {
this.type = type;
this.voice = voice;
}
}
class Main {
public static void main(String[] args) {
// Write code here
// Don't change below this line
System.out.println(cow.type + " is making " + cow.voice);
System.out.println(dog.type + " is making " + dog.voice);
}
}All lessons in Basics of Classes and Objects in Java
1Introduction
Introduction