From the course: Programming Foundations: Object-Oriented Design

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Class with multiple constructors

Class with multiple constructors - Python Tutorial

From the course: Programming Foundations: Object-Oriented Design

Start my 1-month free trial

Class with multiple constructors

- We've defined a constructor to instantiate our spaceship object, and it sets the callsign attribute to a value of the nameless ship. But, what if I don't want all of the ships we instantiate to have a callsign of the nameless ship? That'd get confusing. - Well, most languages will let us create multiple constructor methods through a process called overloading, which allows a class to have more than one method with the same name, but different sets of input parameters. To do that in Java, we'll create a second method in this spaceship class, also called spaceship, but this one takes a parameter. Just a string, which I've called name and that gets assigned to the callsign variable. Now when we instantiate a spaceship object, we have two ways of doing it. We can use the word new with no parameters, like before, which will call the first constructor method to give us the nameless ship, or, we can use the word new, along with a string parameter. When we include the string parameter, it's…

Contents