Informatik II (D-ITET) Übungsstunde 6, 14.04.2016 Hossein Shafagh, shafagh@inf.ethz.ch Distributed Systems Group, ETH Zürich
Ablauf Kurze Besprechung von Übung 5 More Java insights (Inheritance & Interfaces) Hinweise für Übung 6 2
Lösung U5 Bemerkungen Variablen & Methoden beginwithlowercase, areverydescriptiveand uppercaseseparated einemethodediesehrlangennamenhat() Klassen mit Grossbuchstaben: class MeineKlasse{ C++ notation: Membervariablen (Attribute) beginnen mit m (mvalue, mnext), temporäre und übergebene Parameter nicht (int tmp) Bitte, mehr kommentieren! 3
Lösung U5A1, A2, A3 - einfach verkettete Liste Lösung U5A4 - Stack mit Liste Demo Time 4
Ablauf Kurze Besprechung von Übung 5 More Java insights (Inheritance & Interfaces) Hinweise für Übung 6 5
Java Inheritance & Interfaces Outline Person class example Inheritance Type compatibility Polymorphism instanceof Visibility rules Constructor and super() Final methods and class Abstract classes and methods Interfaces Abstract classes vs. interfaces 6
Class Person Person Name Age Address PhoneNumber tostring getname getage getaddress getphonenumber setaddress(newaddress) setphonenumber(newphonenumber) Attributes Accessors Mutators Getter and Setter Methods 7
Class Person - Implementation public class Person { private String m_name; private int m_age; private String m_address; private String m_phone; public Person(String name, int age, String address, String phone) { m_name = name; m_age = age; m_address = address; m_phone = phone; public String tostring() { return getname() + " is " + getage() + "old and lives in " + getaddress(); public String getname() { return m_name; public int getage() { return m_age; public String getaddress() { return m_address; public String getphonenumber() { return m_phone;... 8
Class Student Person Name Age Address PhoneNumber tostring() getname() getage() getaddress() getphonenumber() setaddress(newaddress) setphonenumber(newphonenumber) Student Name Age Address PhoneNumber Legi tostring() getname() getage() getaddress() getphonenumber() getlegi() setaddress(newaddress) setphonenumber(newphonenumber) 9
Class Student Student erweitert ein bestehendes Konzept, die Klasse Person enthält ein zusätzliches Feld: m_legi mit Getter: getlegi() public class Student extends Person { private String m_legi; public Student(String name, int age, String address, String phone, String legi){ super(name, age, address, phone); m_legi = legi; public String tostring() { return getname() + " is " + getage() + "old, lives in " + getaddress() + " and has legi-nr.: " + getlegi(); public String getlegi() { return m_legi; 10
Class Student Student definiert ein Konstruktor ruft Basisklassenkonstruktor mit super auf public class Student extends Person { private String m_legi; public Student(String name, int age, String address, String phone, String legi){ super(name, age, address, phone); m_legi = legi; public String tostring() { return getname() + " is " + getage() + "old, lives in " + getaddress() + " and has legi-nr.: " + getlegi(); public String getlegi() { return m_legi; 11
Class Student Student definiert die Methode tostring() neu. public class Student extends Person { private String m_legi; public Student(String name, int age, String address, String phone, String legi){ super(name, age, address, phone); m_legi = legi; public String tostring() { return getname() + " is " + getage() + "old, lives in " + getaddress() + " and has legi-nr.: " + getlegi(); public String getlegi() { return m_legi; 12
Inheritance Student extends Person Student can: Add new fields m_legi Add new methods getlegi() Override existing methods tostring() Student cannot: Remove fields Remove methods 13
Why inheritance? Better design Code reuse Code maintenance Abstraction of the real world 14
Static & Dynamic Cast Person Student Employee Person p = new Person(...); Student s = new Student(...); Employee e = new Employee(...); Person ps = s à ok Person pe = e à ok Student sp = p à compile error Student sps = ps à compile error Student dsps = (Student) ps à ok Employee deps = (Employee) ps à runtime error 15
Static & Dynamic Cast Person Student Employee Person p = new Person(...); Student s = new Student(...); Employee e = new Employee(...); p instanceof Person à true p instanceof Student à false s instanceof Person à true s instanceof Student à true 16
The Object class in Java The Object class in Java Is a superclass for all other classes defined in Java's class libraries, as well as for user-defined Java classes. This does not include base types (char, int, float, etc.) they are not classes! When a class is defined in Java, the inheritance from the Object class is implicit, therefore: public class MyClass {... is equivalent to: public class MyClass extends Object {... 17
The Object class in Java Object Person Student Employee Quelle: sun.com 18
Visibility Rules private members Private members in the base class are not accessible to the derived class, and also not to anyone else protected members Protected members are visible to methods in a derived class and also methods in classes in the same package, but not to anyone outside public members Everyone 19
Final Methods and Classes A derived class Can accept the base class methods Or can override the base class methods A method declared as final in the base class cannot be overridden by any derived class A final class cannot be extended! E.g. Integer, Character,... 20
Abstract Classes Abstract method Is a method that all derived classes must implement Abstract class A class that has at least one abstract method If a class derived from an abstract class fails to override an abstract method, the compiler will detect an error Eclipse: 'Hint-Bulb' provides help! 21
Interface The interface in Java is the ultimate abstract class A class can implement many interfaces A class implements an interface if it provides definitions for all the methods declared in the interface So, both abstract classes and interface provide a specification of what subclasses must do But... 22
Abstract Class vs. Interface Abstract class An abstract class can provide complete code, default code, and/or just stubs that have to be overridden Interface An interface cannot provide any code, much less default code May declare methods as protected abstract All methods declared are implicitly public abstract A class may extend only one abstract class A class may implement several interfaces http://java.sun.com/docs/books/tutorial/java/iandi/index.html 23
Example: Interface IStack public interface IStack { int size(); void push(object obj); Object pop(); Object peek(); boolean empty(); public class MyStack implements IStack { private int size; public int size() { return size; public void push(object obj) {...... 24
Example: Abstract Class BaseStack public abstract class BaseStack implements IStack { public abstract int size(); public abstract void push(object obj); public abstract Object pop(); public Object peek() { Object top = pop(); push(top); return top; public boolean empty() { return size() == 0; public class MyStack extends BaseStack { private GenericList first; public Object peek() { return first.value;... 25
Factory-Klassen Intuitiv: Die Idee hinter Interfaces ist ja, dass Funktionalität austauschbar ist. Aber: Was bringt die ganze Austauschbarkeit, wenn ich an x Stellen im Code etwas verändern muss, um Objekte auszutauschen Daher: Factory-Klassen 26
Factory-Klassen interface Thing getthing(), setthing() class SimpleThing implements ThingInterface class ComplexThing implements ThingInterface «Traditionelle» Implementierung (an 100x Stellen im Code...): Thing mything = new SimpleThing(); Implementierung mit «ThingFactory»: Thing mything = ThingFactory.createThing(); 27
Factory-Klassen class ThingFactory { public static Thing creatething() { return new SimpleThing(); Demo Time 28
Ablauf Besprechung von Übung 5 More Java insights (Inheritance & Interface) Hinweise für Übung 6 29
Tipps zu U6 A1: Klassen, Schnittstellen, Typumwandlungen A2: Schnittstellen und Implementierungen A3: Polymorphie A4: Array-Listen und Generics 30
Tipps zu U6.A1 UML A keyword represents an interface Notation for the dependance of the instantiation of the interface. Thermal sensor instantiates the isensor interface Keyword Property Section with attributes (detailed representation) Privatkunde as a specialized Person Section with operations (detailed representation http://de.wikipedia.org/wiki/klassendiagramm 31
Tipps zu U6.A2 Fabrikmethode Die Fabrikmethode erstellt ein Objekt, was ein bestimmtes Interface verwirklicht, aber das Innere Funktionsweise des Objektes ist versteckt. à Programmer 1 implementiert verschiedene Listen, die alle das Interface IList verwirklichen à Programmer 2 benutzt Listen, will aber nichts über die Funktionsweise wissen. Wenn Programmer 1 eine neue Implementierung schreibt, muss Programmer 2 im Code alle Zeilen new ListA() auf new ListB() umschreiben. à Programmer 1 stellt eine Fabrikmethode zu verfügung, und Programmer 2 kann immer z.b Factory.giveMeNewList() aufrufen, und kriegt ein Objekt von neuester Implementierung der IList Interface zurück. 32
Tipps zu U6.A3 Generische Listen Übungsserie 5 Elemente der Liste: Ganzzahlen int Übungsserie 6 Elemente der Liste: generische Objekte Object Selber eine Utility-Klasse erstellen: ListUtils implements IListUtils: handhabt generische Listen Vergleiche mit den Utility-Klassen aus A1 & A3 von Übung 5 Diesmal wird die Utility Klasse instantisiert (nicht mehr static) 33
Tipps zu U6.A3 Generische Listen class List { int value; List next; public List(int v, List e){ value = v; next = e; value v next e value v next e 34
Tipps zu U6.A3 Generische Listen class GenericList { Object value; GenericList next; public GenericList(Object v, GenericList e){ value = v; next = e; value v next e value v next e 35
Tipps zu U6.A3a und c Generische Listen Methoden sind nicht mehr static! U5A1: tostring, add, size können praktisch übernommen werden U5A3: sort ähnlich (gleiche Idee) Minimale Anpassung, damit es mit generischen Object-Elementen funktionieren kann: Interface Comparable public interface Comparable { boolean smallerthan(comparable rhs); Ihr dürft ohne Prüfung nach Comparable casten 36
Tipps zu U6.A3b Generische Listen Trivial Werden in den Tests für eure Liste verwendet! zuerst implementieren dann Fehler in GenericList suchen J 37
Tipps zu U6.A4 Generics U6.A3 Generics Alle Klassen erben von Object (abstract base class) cast beim Ausnehmen aus der Kontainer (hier List) MyType Elem = (MyType) Kollektion.getNext(); sowas kann in Laufzeit zur ClassCastException führen. Besser so: Object obj = Kollektion.getNext(); if( obj instanceof MyType ) dosomething( (MyType)obj ); MyType Object MyType MyType next MyType next mylist next 38
Tipps zu U6.A4 Generics U6.A4 Generics Kollektion mit Java Generics (generic class) class MyPair<T> { public T first, second; Ein Objekt pair vom Typ MyPair<Float> enthält zwei Float- Referenzen: pair.first und pair.second Ein Objekt pair vom Typ MyPair<Int> enthält zwei Int-Referenzen: pair.first und pair.second Vorteil von generics: Typenprüfung durch Compiler auch bei der Aufnahme in den Kontainer à kein dynamic cast nötig bei Ausnahme 39
Tipps zu U6.A4 Generics ArrayList Container Zweifach geschachtelt: ArrayList enthält Gruppen ArrayList<ArrayList<Student>> groups; Gruppen enthalten Studenten ArrayList<Student> group; Filter: Testat erhalten kann 40
Tipps zu U6.A4 Generics a. FilterFactory und (leere) IFilter-Implementierung Input: ArrayList von Gruppen, die eigentlich ArrayLists von Studenten sind Output: ArrayList von Studenten, die das Testat erhalten. b. Implementieren von filterraw (compatibility, prior Generic!) Keine Generics: ArrayList als Raw Type (Compilerwarnungen) Alle Studenten rausfiltern, die nicht genug Punkte für das Testat haben... Beim Ausnehmen zuerst auf ArrayList, dann auf Student casten Generel sollte man nie Raw Types im neuen Code benutzten! c. Implementieren von filtergeneric ArrayList<T> zeigt an, was darin gespeichert ist Type checking beim Hinzufuegen zur Liste ArrayList<T> liefert direkt Objekte des korrekten Typs (kein casting mehr nötig) 41
14.04 fällt aus! Bitte andere Gruppen besuchen!