JetBrains Academy: Multiple constructors - Kamil-Jankowski/Learning-JAVA GitHub Wiki
JetBrains Academy: Multiple constructors
Movie:
You are given a class named Movie. Write two constructors for the class.
The first constructor should take three arguments (title, desc, year) and initialize the corresponding fields.
The second one should take only two arguments (title, year) and initialize name and year. In this case, the field desc should have a value "empty".
class Movie {
private String title;
private String desc;
private int year;
public Movie(String title, int year){
this.title = title;
this.desc = "empty";
this.year = year;
}
public Movie(String title, String desc, int year){
this.title = title;
this.desc = desc;
this.year = year;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public int getYear() {
return year;
}
}
Time:
Here's a class named Time with three fields: hours, minutes and seconds.
Add three constructors to the class:
- The first one takes only
hoursand initializes this field; - The second one takes
hoursandminutesand initializes the corresponding fields; - The third one takes
hours,minutesandsecondsand initializes all fields.
class Time {
int hours;
int minutes;
int seconds;
public Time(int h){
this.hours = h;
}
public Time(int h, int m){
this(h);
this.minutes = m;
}
public Time(int h, int m, int s){
this(h, m);
this.seconds = s;
}
}
Employee:
Here's a class named Employee with three fields: name, salary, address.
Add three constructors to the class:
- the first one is the no-argument constructor, it should initialize string fields with the value "unknown", the
salaryis 0; - the second one takes
nameandsalary, and then initializes the corresponding fields, the address is "unknown"; - the third one takes
name,salary,addressand initializes all fields.
class Employee {
String name;
int salary;
String address;
public Employee(){
this.name = "unknown";
this.salary = 0;
this.address = "unknown";
}
public Employee(String name, int salary){
this.name = name;
this.salary = salary;
this.address = "unknown";
}
public Employee(String name, int salary, String address){
this.name = name;
this.salary = salary;
this.address = address;
}
}
Phone:
Below is a class named Phone. It has four fields: ownerName, countryCode, cityCode and number.
Add two constructor to the class:
- the first one takes
ownerNameandnumberand initializes the corresponding fields; - the second one takes
ownerName,countryCode,cityCode,numberand initializes all fields.
class Phone {
String ownerName;
String countryCode;
String cityCode;
String number;
public Phone(String ownerName, String number){
this.ownerName = ownerName;
this.number = number;
}
public Phone(String ownerName, String countryCode, String cityCode, String number){
this.ownerName = ownerName;
this.countryCode = countryCode;
this.cityCode = cityCode;
this.number = number;
}
}