1Object Oriented Programming 1 Lecture 2 Agenda Object Oriented Programming in Java Lecture & Lab Do the OO Selftest in WebCT! Don’t forget to read Chapter 1 and 2! COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 2 What is Java? An object-oriented programming language Designed by SUN in the 1990s Inventor James Gosling Idea: Programming language for consumer electronics Design Write once run everywhere (WORA) i e platform COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 3 , , . ., independence Like C/C++ but much simpler Fully object oriented and has strict type checking Built-in and enforced exception handling No Pointers! Success Story: Became internet programming language (applets, servelets, etc.) 2How does Java run Java runs within a virtual machine (JVM) Virtual machine needs to be provided for the platform (e.g., Windows XP, Linux, OS X,..) COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 4 myClass.java myClass.class JVM javac java Example program Print “Hello World!” public class Example { public static void main(String[] args){ System.out.println(“Hello World!”); } COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 5 Names are case sensitive main() method is entry point of application Compile program with javac Example Run program with java Example } Classes and objects Class defines the structure and behavior of objects Objects are instances of a class stored in memory and hold values methods can be invoked for an object bli l { COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 6 pu c c ass Car string Type; void moveTo(string Loc); } Name: “KIA”Name: “VW” Class: Objects: 3Class A class defines a new type Declaring instance variables defines structure Declaring instance methods defines behavior public class Car { St t COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 7 string Type; voit setType(string type); void moveTo(string Loc); } Behavior ruc ure Creating Objects A new instance of a class is created with new(params,…); returns a new instance of class . Often called instantiation. COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 8 Example new Car(); new Car(“KIA”); Constructor Constructor is a special method in a class Using new invokes class’ constructor It must be the same name as class No return type specified Generally used to initialize member variables COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 9 A default constructor is supplied public class Car { public Car() {…} public Car(String type) {…} } 4Instance Methods A methods of a class Instance of the class can perform the method Method can only be performed by an instance Methods COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 10 provide functionality to the user (other code) can directly access instance variables and invoke other instance methods Rule of thumb: user should not access variables directly. Example: Instantiation & Method Call // create instance of class Car Car myCar = new Car(); // invoke method COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 11 myCar.moveTo(“Cairns”); this Methods can refer to the object itself with this Can be used to disambiguate and clarify Example: class Car { COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 12 … public boolean faster(Car other) { return (this.maxSpeed > other.maxSpeed); } … } 5null Object reference null reference value that does not point to an object COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 13 Car obj; … // if obj is null, instantiate new object if (obj == null) { obj = new Car(); } Object Destruction Programmer does not need to de-allocate objects Java uses garbage collection Garbage collector finds unreferenced objects and reuses memory COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 14 // create instance of class Car Car myCar = new Car(); // invoke method myCar.moveTo(“Cairns”); // indicate GC that myCar is not used myCar = null; Inheritance Sometimes one entity type includes some objects which belong to a more restricted entity type as well subclass object “IS-A” superclass object superclass generalizes subclass A class can inherit feature of a superclass COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 15 The original class is called superclass The extended class is called subclass Inheritance is a fundamental concept in OO Existing code can be reused New classes can be defined by their differences to existing classes 6Examples Examples Student “is-a” Person ChequeAccount “is-a” Account Fridge “is-a” ElectricalAppliance class Student extends Person { COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 16 … } class ChequeAccount extends Account { … } Inheritance (cont’d) A class can only extend one parent Implicitly extend Object if nothing else is declared Subclass has all instance variables and methods of th t COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 17 e paren Plus new instance variables Plus new methods Methods of the superclass can be overwritten! extends example class ElectricalAppliance { protected int energyRating; // other fields public void switchOn() { class Fridge extends ElectricalAppliance { protected int freezerCapacity; // other added fields COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 18 // code body here } // more methods } public void defrost() { // code body here } // other added methods } Fridge implicitly has protected int energyRating public void switchOn() 7UML diagrams UML notation for conceptual models (or for OO code structure) Draw each class as a rectangle Inheritance is arrow with ElectricalAppliance COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 19 triangle head From subclass to superclass Fridge WashingMachine Access modifiers The subclass object has inherited fields and methods Can they be used? use is controlled by access modifiers private public protected COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 20 (default) [no modifier stated] To be used in added code in the subclass, make fields and methods in superclass either protected or public Access modifiers public: can be used from anywhere provided a reference exists to an object of the class (or to an object of subclass) private: can only be used in the code of the class itself But that could be in executing a method of COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 21 another object instance of the class! protected: can only be used in code in the class, or in a subclass 8Subclass Constructor The first statement in any constructor of the subclass should be a call to some constructor of the superclass Syntax is super(…); U ll l t t i iti li th COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 22 sua y, superc ass cons ruc or n a ses e inherited instance variables using a subset of the parameters in the subclass constructor Then continue, initialising added instance variables Points to note for Inheritance Superclass can itself extend another class Example: ElectricalAppliance extends Object Subclass implicitly gets fields and methods in superclass including those the superclass inherited Explicit code in added subclass methods can modify COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 23 or use accessible fields that are inherited, and can call accessible methods that are inherited Hierarchy A class can directly extend only one other class “extends Object” is implicit if nothing else is said COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 24 Indirectly inherit from superclasses of the direct superclass So the classes form a tree based on extends relationship 9Warnings I Inheritance should only be used for generalisation when subclass object “is-a” superclass object Otherwise use delegation to get code re-use ith t li ti COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 25 w ou genera sa on Example: SportsTimekeeper with getCurrentTime() does not inherit from Clock Warnings II Inheritance isn’t appropriate for all generalisation situations when subsets have the same structure of variables, and same code, or when object can change between subsets, or when object can belong to several subsets at once then use one class COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 26 with instance variable to indicate subset eg instance variable rank in class Soldier instead of separate subclasses for General, Colonel, Private Subtype definition One type is a subtype of another through a chain of extends relationships Example: Person, Student class Person class Student extends Person Student is sub-type of Person. COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 27 Person p; Student s = new Student(“Fred”); // assignment possible because Student // is subclass of student (and a subtype) p=s; // not possible: s=p; !! 10 Static and Dynamic Type Static Type: The type with which the variable is declared. Known at compile time. The same for all uses of a variable Dynamic Type: COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 28 The type which was used when constructing the object that the variable is actually referencing Known only at run time. Can be different each time a particular line is reached Class or primitive, only Late binding Given a variable on which a method is called The static type of the variable determines if the call is legal But which code is actually executed is d t i d b th d i t f th COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 29 e erm ne y e ynam c ype o e variable (at runtime, when the call occurs) Another Example of Static and Dynamic Type ElectricalAppliance myEquipment; myEquipment = new Fridge( ); //(A) … … … … ElectricalAppliance onLoan = new WashingMachine(); myEquipment = onLoan; //(B) COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 30 myEquipment at (A) Static Type: ElectricalAppliance Dynamic Type: Fridge myEquipment at (B) Static Type: still ElectricalAppliance Dynamic Type: WashingMachine 11 Polymorphism and subtyping Assignment x = v; is syntactically correct provided static type of v is subtype of static type of x Dynamic type of x after the assignment is dynamic type of v Call x.method(); is syntactically correct provided static type of x has method() in its definition COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 31 Directly, or inherited through extends Which code gets executed is determined by dynamic type of x Substitutability The dynamic type of a variable or expression must always be either the same as, or a subtype of, the static type This ensures that the dynamic type has code COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 32 for any method that will be called the compiler checked that the method was appropriate for the static type! Interface Define a type which captures what we can do with objects of similar classes It is given as an interface in Java Indicates method signatures (name, argument types, return type) but not method body COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 33 Note: no constructor! In client code, a variable can be declared with an interface as type 12 interface Repairable { boolean isWorking(); Define an interface Note: no method body COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 34 void repair(); } The interface is in a file Repairable.java, just like a class Note: interface names often end in “able” since they describe what the type can do Interface as type Declare an instance variable in client code can have interface as its type Example: Repairable r = …; Also use interface for type of local variable, or COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 35 method argument But: cannot create object of type Repairable Class implements interface To use a class in contexts where interface is the type, you must set up the class to implement the interface This puts obligation on code of class it t h th d i th i t f ith COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 36 mus ave every me o n e n er ace w exactly the correct signature and with public access it can also have more methods and instance variables 13 Example class WashingMachine implements Repairable { public boolean isWorking() { // code for this method } bli id i () { COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 37 pu c vo repa r // code for this method } // other methods // instance variables } Using an interface Assign to a variable whose type is some interface any object whose type implements the interface note: you can’t construct from the interface, only from classes! Call a method on the variable whose type is some COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 38 interface as long as the method is part of the interface Example allowed assignment WashingMachine w = new WashingMachine(); Repairable r = w; if (!r.isWorking()) { i () COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 39 methods in the Repairable interface r.repa r ; } 14 Casting Sometimes there is an variable whose static type is an interface, but as programmer you know what the dynamic type is eg because you know which text constructed it You can’t simply call a method of the variable that is COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 40 missing from the static type interface Instead, cast the variable into its static type then call the method Casting example Fridge f = new Fridge(); … Repairable r = f; // can’t call r.defrost(); // as defrost() not in Repairable interface COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 41 Fridge f1 = (Fridge) r; f1.defrost(); // this is legal // compressed syntax ((Fridge) r).defrost(); an expression whose static type is Fridge If dynamic type is not what you try to cast it to, you get an Exception at run-time Avoid this by checking first Instanceof() Query if (r instanceof Fridge) { COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 42 f = (Fridge) r; // do things with f } else { // do something instead } 15 Thanks! COMP5028 Object-Oriented Analysis and Design © Y. Zhou, and B. Scholz, School of IT, The University of Sydney 43