Commit c5313972 by Patryk Czarnik

Enkapsulacja - początek

parent 39174a5d
package p11_enkapsulacja;
public class Osoba {
private String imie, nazwisko;
private int wiek;
public Osoba(String imie, String nazwisko, int wiek) {
this.imie = imie;
this.nazwisko = nazwisko;
this.wiek = wiek;
}
public String toString() {
return imie + " " + nazwisko + " (" + wiek + " lat)";
}
}
package p11_enkapsulacja;
public class Przyklad {
public static void main(String[] args) {
Osoba ola = new Osoba("Ola", "Malinowska", 30);
System.out.println(ola);
Student student = new Student("Jan", "Kowalski", 20, "medycyna", 1);
student.dodajOcene(4);
student.dodajOcene(4);
student.dodajOcene(5);
System.out.println(student.sredniaOcen());
}
}
package p11_enkapsulacja;
import java.time.LocalDate;
import java.util.Arrays;
public class Student extends Osoba {
private String kierunek;
private int rok;
// Ukrywamy szczegóły implementacji - klient nie musi wiedzieć, w jaki sposób przechowujemy oceny studenta ("to nasza prywatna sprawa")
// Żadna inna klasa nie może odwoływać się bezpośrednio do tej tablicy.
private int[] oceny = new int[10];
private int iloscOcen = 0;
public Student(String imie, String nazwisko, int wiek, String kierunek, int rok) {
super(imie, nazwisko, wiek);
this.kierunek = kierunek;
this.rok = rok;
}
public String getKierunek() {
return kierunek;
}
public void setKierunek(String kierunek) {
this.kierunek = kierunek;
}
public int getRok() {
return rok;
}
public void setRok(int rok) {
this.rok = rok;
}
public void dodajOcene(int ocena) {
if(iloscOcen == oceny.length) {
oceny = Arrays.copyOf(oceny, oceny.length*2); // mniej więcej coś takiego robi ArrayList oraz StringBuilder
}
oceny[iloscOcen++] = ocena;
}
public double sredniaOcen() {
double suma = 0.0;
for (int i = 0; i < iloscOcen; i++) {
suma += oceny[i];
}
return suma / iloscOcen;
}
}
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