Visibility.java 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. public class Student {
  2. // die Attribute sind nun nach außen nicht mehr sichtbar
  3. private String name;
  4. private int semester;
  5. private int matriculationNumber;
  6. public Student(String name, int semester, int matriculationNumber) {
  7. // hier wird wie gewohnt alles initialisiert
  8. }
  9. }
  10. public class Main {
  11. public static void main(String[] args) {
  12. Student maxMustermann = new Student("Max Mustermann", 3, 1234567);
  13. // hier bekommt man nun einen Compilerfehler
  14. maxMustermann.matriculationNumber = 3141592;
  15. // ...
  16. }
  17. }
  18. public class Student {
  19. // ... Attribute, Konstruktor usw. ...
  20. // die getter-Methode für das Attribute 'name'
  21. public String getName() {
  22. return this.name;
  23. }
  24. // ... weitere getter-Methoden usw. ...
  25. }
  26. public class Main {
  27. public static void main(String[] args) {
  28. Student maxMustermann = new Student("Max Mustermann", 3, 1234567);
  29. // liest den Namen und gibt ihn aus
  30. System.out.println(maxMustermann.getName());
  31. // ...
  32. }
  33. }