Last active
March 4, 2019 15:37
-
-
Save avermeulen/36df9abaab36dcbc1d15419531c17d94 to your computer and use it in GitHub Desktop.
Examples using constructors using Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person { | |
private String lastName; | |
private String firstName; | |
public Person(String firstName) { | |
this.firstName = firstName; | |
} | |
public Person(String firstName, String lastName) { | |
this(firstName); | |
this.lastName = lastName; | |
} | |
public String greet() { | |
if (firstName != null && lastName != null) { | |
return "Hello, " + firstName + " " + lastName; | |
} | |
return "Hello, " + firstName; | |
} | |
public String getFirstName() { | |
return firstName; | |
} | |
@Override | |
public String toString() { | |
if (firstName != null && lastName != null) { | |
return firstName + " " + lastName; | |
}; | |
return firstName; | |
} | |
} | |
class Couple { | |
Person guy; | |
Person girl; | |
public Couple(Person guy, Person girl) { | |
this.guy = guy; | |
this.girl = girl; | |
} | |
@Override | |
public String toString() { | |
return guy + " is dating " + girl; | |
} | |
} | |
public class Main { | |
public static void main(String[] args) { | |
Person yegan = new Person("Yegan", "James"); | |
Person alice = new Person("Alice", "Jansseune"); | |
System.out.println(yegan.greet()); | |
System.out.println(alice.greet()); | |
Couple yeganAndAlice = new Couple(yegan, alice); | |
System.out.println(yeganAndAlice); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment