Commit 51174908 by Patryk Czarnik

dziedziczenie - początek

parent cd0acb7a
package p11_klasy.podstawy;
public class Dziedziczenie {
public static void main(String[] args) {
System.out.println("Osoba:");
Osoba osoba = new Osoba();
System.out.println(osoba);
osoba.imie = "Ala";
osoba.nazwisko = "Kowalska";
osoba.wiek = 30;
System.out.println(osoba);
// Osoba posiada tylko te elementy, które pochjodzą z klasy Osoba, a nie posiada tych dodanych w klasie Student
// osoba.kierunek = "podróżniczka";
// System.out.println(osoba.kierunek);
System.out.println();
System.out.println("Student:");
Student student = new Student();
System.out.println(student);
// Obiekt Student posiada wszystkie te pola i metody, które zostały zdefiniowane w klasie Osoba
student.imie = "Adam";
student.nazwisko = "Abacki";
student.wiek = 20;
System.out.println(student);
student.przedstawSie();
// oraz dodatkowo pola i metody zdefiniowane w klasie Student
student.kierunek = "medycyna";
student.rok = 1;
System.out.println(student.imie + " studiuje " + student.kierunek + " na " + student.rok + " roku");
System.out.println(student.sredniaOcen());
// Dziedziczenie zapewnia nie tylko to, że dostępne są odziedziczone pola i metody,
// ale też na poziomie logicznym "Student jest Osobą"
if(student instanceof Osoba) {
System.out.println("Student jest osobą");
} else {
System.out.println("Student nie jest osobą");
}
// We wszystkich miejscach kodu, w które można by włożyć obiekt klasy Osoba, można też włożyć obiekt klasy Student.
// Obiekt Student może być wpisany do zmiennej typu Osoba
Osoba ktos = student;
System.out.println(ktos + " jest klasy " + ktos.getClass());
System.out.println();
// Student może kupić piwo
Sklep sklep = new Sklep("Lidl", 6);
sklep.sprzedajPiwo(student);
sklep.sprzedajPiwo(ktos);
System.out.println();
// Student może być właścicielem konta
Konto kontoStudenckie = new Konto(1313, 123, student);
System.out.println(kontoStudenckie);
System.out.println();
// Kwestia konstruktorów
// W Javie konstruktory nie są dziedziczone z nadklasy.
// Z faktu, że w Osoba istnieje konstruktor typu (String, String, int) nie wynika istnienie takiego konstruktora w klasie Student
// Student student2 = new Student("Marek", "Markowski", 23);
Student student3 = new Student("Marek", "Markowski", 23, "informatyka", 4);
System.out.println(student3);
System.out.println(student3.imie + " studiuje " + student3.kierunek + " na " + student3.rok + " roku");
}
}
package p11_klasy.podstawy;
public class Student extends Osoba {
String kierunek;
int rok;
public Student() {
}
public Student(String imie, String nazwisko, int wiek, String kierunek, int rok) {
super(imie, nazwisko, wiek);
this.kierunek = kierunek;
this.rok = rok;
}
double sredniaOcen() {
return 4.5;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment