Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Last active April 4, 2025 17:37
Show Gist options
  • Save thinkphp/973c7b9a1847eaf489e80d5cc82167a6 to your computer and use it in GitHub Desktop.
Save thinkphp/973c7b9a1847eaf489e80d5cc82167a6 to your computer and use it in GitHub Desktop.
Aggragation
class Adresa {
private String strada;
private String oras;
private String codPostal;
public Adresa(String strada, String oras, String codPostal) {
this.strada = strada;
this.oras = oras;
this.codPostal = codPostal;
}
// Override toString() to display address details
@Override
public String toString() {
return "Adresa: " + strada + ", " + oras + ", " + codPostal;
}
}
class Student {
private String nume;
private Adresa adresa; // Aggregation - Student "has a" Address
public Student(String nume, Adresa adresa) {
this.nume = nume;
this.adresa = adresa;
}
// Override toString() to display student details
@Override
public String toString() {
return "Student: " + nume + ", " + adresa;
}
}
public class Main {
public static void main(String[] args) {
// Creating an address object
Adresa adresa = new Adresa("Strada Exemplu", "București", "123456");
// Creating student objects
Student student1 = new Student("Ion", adresa);
Student student2 = new Student("Maria", adresa); // Address can be shared
// Printing the details
System.out.println(student1);
System.out.println(student2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment