Presentation is loading. Please wait.

Presentation is loading. Please wait.

1. Everything is an object 2. A program is a set of objects that interact by sending messages (i.e. function calls) 3. Each object has its own state 4.

Similar presentations


Presentation on theme: "1. Everything is an object 2. A program is a set of objects that interact by sending messages (i.e. function calls) 3. Each object has its own state 4."— Presentation transcript:

1

2 1. Everything is an object 2. A program is a set of objects that interact by sending messages (i.e. function calls) 3. Each object has its own state 4. Every object has a type (i.e. class) 5. All object of the same type can receive the same set of messages 6. Every object has state, behavior, identity

3  a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, and the relationships between the classes.  Examples

4 1. Inheritance 2. Polymorphism 3. Late (dynamic) binding

5  One form of software reuse is composition, in which a class has as members references to objects of other classes.

6  A class can have references to objects of other classes as members.  This is called composition and is sometimes referred to as a has-a relationship.

7  Date.java  (1 of 3)

8  Date.java  (2 of 3) Validates month value Validates day value

9  Date.java  (3 of 3) Check if the day is February 29 on a leap year

10  Employee.jav a Employee contains references to two Date objects Implicit calls to hireDate and birthDate ’s toString methods

11  EmployeeTest.ja va Create an Employee object Display the Employee object

12

13

14  Inheritance provides us with a way of: ◦ taking advantage of similarities between objects from different classes ◦ building new classes that are extensions of existing classes

15  How is a student like a person?  Well, every student is a person!  Students have all of the “properties” of persons, plus some others.  For example, every person has a name and an age  and so does every student.  However, not every person is a student.  Every student has a student id and a grade point average, that other persons don't have.

16  In Java, we model a person by a Person class.  In Java, we model a student by a Student class.  Since a student is like a person with extra properties, we say the class Student is a subclass of the class Person.  We also say that Person is a superclass of Student.

17  In general, Person can have other  subclasses as well, say Teacher.  We put all the classes in an inheritance tree with class Object as the root.  We draw the tree with the root at the top.

18 Object Person Student Teacher

19  extends keyword  a subclass inherits all of the instance variables (and methods, except constructors) and all of the static variables (and methods) of its superclass  Singly-rooted class hierarchy ◦ All classes implictly subclass java.lang.Object ◦ Provides equals(), toString(), hashCode() and more basic services  No multiple inheritance

20  Visibility modifier, like public or private  Allows public -like access to subclasses ◦ And to classes in same package  For all other classes it is like private  Rationale: it’s a way to “pass over” to subclasses some feature, without making it visible to client classes.  e.g. field enginePower in MotorVehicle ◦ Makes sense to make it visible to Truck, Car etc.

21  In Java, a subclass inherits all of the methods of its superclass, so they do not have to be re-implemented  However, you can also override any method if you want to  Overriding is not the same as overloading!  In addition, you can add some code to an inherited method, using the super object reference.

22  Costructors are NOT inherited  A subclass instance includes a superclass instance ◦ Objects are constructed/initialized top-down ◦ Superclass constructor must be called first  Which constructor? ◦ Default superclass constructor is implicitly called ◦ If it does not exist, compiler will complain ◦ If programmer wants another superclass constructor to be called, she must specifiy that super() keyword

23 public class Person { // Each instance represents a Person. // Constructors public Person() { // Set the name “unknown” and height name = "unknown"; Height = 160; //… } public Person(String nameString) { // Set the given name and height this( ); // do the 0 argument constructor first this.name = nameString; }

24 public class Student extends Person { // Each instance represents a Student. public Student() { // Set the name: "unknown", height:160, id: 0 this.id = 0; // implicit call to super(); first } public Student(String nameString) { // Set the given name, height:160, id: 0 super(nameString); // explicit call this.id = 0; } public Student(String nameString, int anInt) { // Set the given name height and id, this(nameString); // or super(nameString) this.id = anInt; }

25 class SuperClass { public SuperClass(String param) { System.out.println("SuperClass constructor " + param); } class SubClass extends SuperClass{ public SubClass() { System.out.println("SubClass constructor"); } public SubClass(String param) { super(param); System.out.println("SubClass constructor " + param); } public static void main(String args[]) { SubClass sub = new SubClass(args[0]); } Has no default constructor Call to super() must be 1 st statement in constructor What is going to happen?

26  A variable of some class can then be bound to an instance of that class or any subclass.  Any message that can be sent to an instance of a class can also be sent to an instance of its subclasses.  If the type of a method parameter or the return type of a method is a class, you can use any subclass as well.  The principle of being able to use an instance of a subclass, wherever you can use an instance of a class is called substitutability.

27  Person class has setName (String) method  Student class  Person p = new Person (“Lin”);  Student s = new Student (“Mike”, 9909);  p = new student (“John”, 1230); //p can be bounded to any kind of person  p.setName(“new name”);  s.setName(“new name”); //message setName can be sent to any kind of Person

28  Assume that class Store has a method called register that takes a Person as a parameter: public void register(Person aPerson) { //Register the given Person as a customer. } Store sto; //.. Some code to create sto sto.register(p); sto.register(s);

29  Instance methods and static methods can be overridden in a subclass  Overriding methods shadow the method of the superclass  If there are multiple implementations of a method within the inheritance hierarchy of an object, the one in the “most derived” class (lowest in the tree) overrides the others, even if we refer to the object via a less derived type

30  Overloaded methods are selected by the compiler at compile time  Overridden methods are selected dynamically by the Virtual Machine at runtime  There is a small performance penalty to pay for dynamic binding - VM has to search for the overridden methods in subclasses.

31  Inheritance and Polymorphism  Classic example – easy to understand  All geometric shapes are types in themselves

32  Suppose we’re writing a new, super-powerful drawing program  This program is so powerful, it can draw both circles and squares  And in the future – who knows! – we might be able to draw triangles, and ellipses

33  We define two classes, Circle and Square  Each class has fields size, location, and color  Each implementation also holds an extra integer field called type, that is always set to 1 if it’s a Circle and 2 if it’s a Square

34  As the user draws, we save their drawing as a list of “things,” where a thing can be either a Circle or a Square  To draw things, we have to looks at the type field, and if it’s a 1 it calls method drawCircle() on the thing, and if it’s a 2 it calls drawSquare().

35 + Circle() - drawCircle() - int type = 1 - long size - long color - long coordX - long coordY Circle + Square() - drawSquare() - int type = 2; - long size - long color - long coordX - long coordY Square

36  We define a class Shape that has fields size, location, and color.  We define two more classes, Circle and Square  Each extends Shape  In each of these two subclasses we define a specific draw() method.  Each defines its own algorithm, so Circle’ s draw() draws a circle, and Square ’s draw() draws a square  They override the original draw()

37 + Shape() + draw() - long size - long color - long coordX - long coordY Shape + Square() + draw() Square + Circle() + draw() Circle extends class Drawing { Shape[] myShapes; Shape[] myShapes;... public void refresh () { public void refresh () { for (int i=0;int < myShapes.length;i++) for (int i=0;int < myShapes.length;i++)myShapes[i].draw() }}

38  Both draw() methods use the size, location, and color fields, although these are not directly defined in the subclass. The fields are inherited from the superclass.  We have a list of shapes, and we ask each shape to draw itself.  NOTE: the correct method is called each time: this is polymorphism

39  Polymorphism seems a bit magic ◦ Not only draw() of Shape is overridden … ◦ … But each time the right draw() is invoked!  The code to be executed for each call is not pre-determined by the compiler ◦ Early vs. late binding  Run-time language support resolves what code is to be executed each time ◦ by looking at the actual type of the object involved in the call

40  A cast tells the compiler to perceive an object reference as a different type  Unlike some other languages, Java performs type checking at compile-time and runtime  Casting is only legal between objects in the same inheritance hierarchy:  Can’t cast a Point to a Date, for example! a ClassCastException is thrown if you attempt to cast an object to an incompatible type at runtime

41  Person p = new Person( );  Student s = new Student( );  p = s ; // legal, Substitutability rule  // s = p; // compile-time error, incompatible type  p= new Student();  s = (Student) p; // legal

42  Casting does not change the reference or the object being pointed to. It only changes the compiler/VM’s treatment of the reference  A common usage of Casting: When we take an Object reference out of a Container (e.g. Vector) and cast it to another type (e.g. String) we are performing a narrowing cast

43  Implicitly cast an object to a less derived type (i.e. a class higher up the tree)  If you have an Object that you know is of a more derived type you can downcast it ( narrow)  If you’re not sure of the type of an object, you must use instanceof before performing the cast, to avoid a ClassCastException at runtime

44  The instanceof operator can be used to determine the type of an object at runtime  Use it to compare an object against a particular type  Returns a boolean: ◦ true if the object is of the specified class ◦ false otherwise

45  boolean result;  String aString = “Fred”;  result = (aString instanceof String); // true  result = (aString instanceof Object); // true  result = (aString instanceof Point); // false  aString = null;  result = (aString instanceof String); // false

46  clone()  equals()  finalize()  toString()  hashCode()  notifiy()

47  All classes in Java inherit directly or indirectly from Object, so its 11 methods are inherited by all other classes.  Figure 9.12 summarizes Object ’s methods.  Can learn more about Object ’s methods in the online API documentation and in The Java Tutorial at : java.sun.com/javase-/6/docs/api/java/lang/Object.html or java.sun.com/docs/books/tutorial/java/IandI/ objectclass.html  Every array has an overridden clone method that copies the array.  If the array stores references to objects, the objects are not copied—a shallow copy is performed.  For more information about the relationship between arrays and class Object, see Java Language Specification, Chapter 10, at java.sun.com/docs/books/jls/third_edition/ html/arrays.html (C) 2010 Pearson Education, Inc. All rights reserved.

48

49

50

51  Inheritance hierarchy  Sometimes base class is an entity you want to instantiate  Sometimes it is just an abstract type ◦ Defines a useful set of concepts and functions but not an entity that needs instances  Example: Shape ◦ You instantiate Circles, Squares etc.  abstract keyword

52  A class is abstract (can’t be instantiated) if: ◦ Has 1 or more abstract methods ◦ … or is itself declared abstract ◦ Invoking new on an abstract class makes compiler complain  Abstract methods have no code ◦ Declare an API without defining its implementation ◦ Implementation is delegated to non-abstract subclasses satisfying the same API abstract class Shape { … } public abstract void doSomething();

53 abstract class Shape{ private long color; Shape(long color) { this.color = color; } public long getColor() { return color; }... public abstract double computeArea(); }

54 Rectangle base height computeArea() Circle radius computeArea() Shape color getColor() computeArea()

55  An abstract class declares an API  Not “pure” API ◦ Some of the implementation is carried out there ◦ Some is delegated to subclasses ◦ Contract plus some content  Makes sense if some of the code logically belongs into the abstract class  Java provides means for defining pure APIs as well, called interfaces  Only contract definition ◦ abstract classes to the extreme

56  Create an interface like you would a class  In a file.java  List methods belonging to the interface  A class can then be declared to implement that interface public interface myInf { void myMethod1(); int myMethod2(int i); } Class myClass implements myInf { public void myMethod1() { } public int myMethod2(int i) { } } must provide public implementations of all myInf methods Class access rules apply to interfaces as well

57  Can subclass interfaces ◦ extends keyword  Can have fields in interfaces ◦ They are public, static and final ◦ To be immediately assigned ◦ Good device for defining sets of constants ◦ Refer to them as. interface subInf extends SuperInf1, superInf2{... }

58  More than just abstract classes to the extreme  While a class can extend only one class … ◦ … it can implement any number of interfaces  A way around the absence of multiple inheritance in Java  Allows to assign and combine freely features and functionality to classes ◦ Actually to their APIs

59 abstract class Bird abstract class FlyingBird interface CanFly + fly() interface CanSwim + swim() class Eagleclass Penguin extends implements

60

61

62  Final keyword can be applied to prevent some of the inheritance effects  final field: i.e. constant  final argument: cannot change data within called method  final method: i.e. cannot override method in subclasses  final class: i.e. cannot subclass it ◦ All of its methods are implicitly final as well  Rationale: design and/or efficiency

63  extends: inherit and specialize  protected : share a field / method with subclasses  abstract : declare contract, delegate (part of) implementation  interface : ◦ pure API, no implementation, not even partial ◦ multiple APIs (  multiple inheritance) ◦ advanced type modeling  final : limits inheritance effects

64  OO and Java ◦ OO concepts ◦ Inheritance ◦ Polymorphism ◦ Late binding ◦ Casting ◦ Abstract classes ◦ Interfaces


Download ppt "1. Everything is an object 2. A program is a set of objects that interact by sending messages (i.e. function calls) 3. Each object has its own state 4."

Similar presentations


Ads by Google