Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CISC370: Inheritance James Atlas. June 17, 2008James Atlas - CISC3702 Questions? Assignment 1 Assignment 1 Review Review.

Similar presentations


Presentation on theme: "1 CISC370: Inheritance James Atlas. June 17, 2008James Atlas - CISC3702 Questions? Assignment 1 Assignment 1 Review Review."— Presentation transcript:

1 1 CISC370: Inheritance James Atlas

2 June 17, 2008James Atlas - CISC3702 Questions? Assignment 1 Assignment 1 Review Review

3 June 17, 2008James Atlas - CISC3703 Review What is Java? What is Java? Primitive data types Primitive data types Arrays Arrays Control flow Control flow Static/Final Static/Final OOP OOP  Objects/Classes/Instances  Encapsulation

4 June 17, 2008James Atlas - CISC3704 Quiz!

5 June 17, 2008James Atlas - CISC3705 Inheritance Build new classes based on existing classes   Allows you to reuse code Start with a Class (superclass) Create another class that extends the class (subclass or derived class)   subclass inherits all of superclass’s methods and fields (unless they’re private )   can also override methods use the same name, but the implementation is different

6 June 17, 2008James Atlas - CISC3706 Inheritance   Subclass adds methods or fields for additional functionality   If the subclass redefines a superclass method, can still call the superclass method on the “super” object Use extends keyword to make a subclass

7 June 17, 2008James Atlas - CISC3707 Rooster class Could write class from scratch, but … Could write class from scratch, but … A rooster is a chicken A rooster is a chicken  But it adds something to (or specializes) what a chicken is/does The is a relationship The is a relationship  Classic mark of inheritance Rooster will be subclass Rooster will be subclass Chicken will be superclass Chicken will be superclass

8 June 17, 2008James Atlas - CISC3708 Rooster class public class Rooster extends Chicken { public Rooster( String name, int height, double weight) { // all instance fields inherited // from super class this.name = name; this.height = height; this.weight = weight; is_female = false; } // new functionality public void crow() {… } … } By default calls super constructor with no parameters

9 June 17, 2008James Atlas - CISC3709 Rooster class public class Rooster extends Chicken { public Rooster( String name, int height, double weight) { super(name, height, weight); is_female = false; } // new functionality public void crow() { … } … } Call to super constructor must be first line in constructor

10 June 17, 2008James Atlas - CISC37010 Constructor Chaining Automatically calls constructor of superclass if not done explicitly Automatically calls constructor of superclass if not done explicitly  super(); What if superclass does not have a constructor with no parameters? What if superclass does not have a constructor with no parameters?  Compilation error  Forces subclasses to call a constructor with parameters

11 June 17, 2008James Atlas - CISC37011 Overriding Methods in Superclass public class Rooster extends Chicken { … // new functionality public void crow() {… } // overrides superclass; greater gains public void feed() { weight +=.5; height += 2; }

12 June 17, 2008James Atlas - CISC37012 Overriding Methods in Superclass public class Rooster extends Chicken { … // new functionality public void crow() {… } // overrides superclass; greater gains public void feed() { // make it relative to Chicken super.feed(); }

13 June 17, 2008James Atlas - CISC37013 Every object is an instance of Object java.lang.Object java.lang.Object Inherited methods Inherited methods  clone Creates and returns a copy of this object.  equals Indicates whether some other object is "equal to" this one.  finalize Called by the garbage collector on an object when garbage collection determines that there are no more references to the object

14 June 17, 2008James Atlas - CISC37014 Aside on finalize() No deconstructors in Java No deconstructors in Java  No explicit freeing of memory Garbage collector calls finalize() Garbage collector calls finalize()  Garbage collector is low-priority thread Or runs when available memory gets tight Or runs when available memory gets tight  Before can clean up memory, object may have generated temp files or open network connections that should be deleted/closed first Benefits of garbage collection? Benefits of garbage collection?

15 June 17, 2008James Atlas - CISC37015 Aside on finalize() Benefits of garbage collection Benefits of garbage collection  Fewer memory leaks Less buggy code Less buggy code But, memory leaks are still possible But, memory leaks are still possible  Code is easier to write Cost: garbage collection may not be as efficient as explicit freeing of memory Cost: garbage collection may not be as efficient as explicit freeing of memory

16 June 17, 2008James Atlas - CISC37016 Every object is an instance of Object java.lang.Object java.lang.Object Inherited methods Inherited methods   getClass Returns the runtime class of an object.   toString Override to customize printout for use in System.out.println()   And others…

17 June 17, 2008James Atlas - CISC37017 Inheritance Tree java.lang.Object java.lang.Object  Chicken Rooster Rooster Call constructor of superclass first Call constructor of superclass first  Know you have the fields of superclass before you implement constructor for your class ObjectChickenRooster

18 June 17, 2008James Atlas - CISC37018 Inheritance Tree java.lang.Object java.lang.Object  Chicken Rooster Rooster No finalize() chaining No finalize() chaining  Should call super.finalize() inside of finalize method ObjectChickenRooster

19 June 17, 2008James Atlas - CISC37019 Shadowing Superclass Fields Subclass has field with same name as superclass Subclass has field with same name as superclass  You probably shouldn’t be doing this!  But could happen Possibly: more precision for a constant Possibly: more precision for a constant field // this class’s field field // this class’s field this.field // this class’s field this.field // this class’s field super.field // super class’s field super.field // super class’s field

20 June 17, 2008James Atlas - CISC37020 Access Modifiers (Revisited) public   Any class can access private   No other class can access (including subclasses) Must use superclass’s accessor/mutator methods protected   subclasses can access   members of package can access   other classes cannot access

21 June 17, 2008James Atlas - CISC37021 Summary of Access Modes Four access modes: Four access modes:  Private – visible to the class only  Public – visible to the world  Protected – visible to the package and all subclasses.  Default – visible to the package what you get if you don’t provide an access modifier what you get if you don’t provide an access modifier

22 June 17, 2008James Atlas - CISC37022 Member Visibility Accessible to Member Visibility PublicProtectedPackagePrivate Defining Class YesYesYesYes Class in same package YesYesYesNo Subclass in different package YesYesNoNo Non-subclass different package YesNoNoNo

23 June 17, 2008James Atlas - CISC37023 Multiple Inheritance In C++, it is possible for a class to inherit (or extend) more than one superclass. In C++, it is possible for a class to inherit (or extend) more than one superclass.  The subclass has the fields from both superclasses This is NOT possible in Java. This is NOT possible in Java.  A class may extend (or inherit from) only one class.  There is no multiple inheritance.

24 June 17, 2008James Atlas - CISC37024 Polymorphism You can use a derived class object whenever the program expects an object of the superclass You can use a derived class object whenever the program expects an object of the superclass object variables are polymorphic. object variables are polymorphic. A Chicken object variable can refer to an object of class Chicken, Hen, Rooster, or any class that inherits from Chicken A Chicken object variable can refer to an object of class Chicken, Hen, Rooster, or any class that inherits from Chicken Chicken[] chickens = new Chicken[3]; chickens[0] = new Chicken(); chickens[1] = new Rooster(); chickens[2] = new Hen();

25 June 17, 2008James Atlas - CISC37025 Polymorphism But, chicken[1] is still a Chicken object But, chicken[1] is still a Chicken objectchicken[1].crow(); will not work Chicken[] chickens = new Chicken[3]; chickens[0] = new Chicken(); chickens[1] = new Rooster(); chickens[2] = new Hen();

26 June 17, 2008James Atlas - CISC37026 Polymorphism Which method do we call if we call Which method do we call if we callchicken[1].feed() Rooster’s or Chicken’s?

27 June 17, 2008James Atlas - CISC37027 Polymorphism Which method do we call if we call Which method do we call if we callchicken[1].feed() Rooster’s or Chicken’s? Rooster’s! Rooster’s!  Object is a Rooster  The JVM figures out its class at runtime and runs the appropriate method. Dynamic dispatch Dynamic dispatch  At runtime, the class of the object is determined. Then, the appropriate method for that class is dispatched.

28 June 17, 2008James Atlas - CISC37028 Dynamic vs. Static Dispatch Dynamic dispatch is a property of Java, not object-oriented programming in general. Dynamic dispatch is a property of Java, not object-oriented programming in general. Some OOP languages use static dispatch where the type of the object variable used to call the method determines which version gets run. Some OOP languages use static dispatch where the type of the object variable used to call the method determines which version gets run. The primary difference is when the decision on which method to call is made… The primary difference is when the decision on which method to call is made…  Static dispatch (C#) decides at compile time.  Dynamic dispatch (Java) decides at run time.

29 June 17, 2008James Atlas - CISC37029 Feed the Chickens! for( Chicken c: chickens ) { c.feed();} Dynamic dispatch calls the appropriate method in each case, corresponding to the actual class of each object. Dynamic dispatch calls the appropriate method in each case, corresponding to the actual class of each object.  This is the power of polymorphism and dynamic dispatch! How to read this code?

30 June 17, 2008James Atlas - CISC37030 Preventing Inheritance Sometimes, you do not want a class to derive from one of your classes. Sometimes, you do not want a class to derive from one of your classes. A class that cannot be extended is known as a final class. A class that cannot be extended is known as a final class. To make a class final, simply add the keyword final in front of the class definition: To make a class final, simply add the keyword final in front of the class definition: final class Rooster extends Chicken {... }

31 June 17, 2008James Atlas - CISC37031 Final methods It is also possible to make a method inside of a class final. It is also possible to make a method inside of a class final.  any class derived from this class cannot override the final methods By default, all methods in a final class are final methods. By default, all methods in a final class are final methods. class Chicken {... public final String getname() {... }... }

32 June 17, 2008James Atlas - CISC37032 Why have final methods and classes? Efficiency Efficiency  the compiler can replace a final method call with an inline method because it does not have to worry about another form of this method that belongs to a derived class.  JVM does not need to determine which method to call dynamically Safety Safety  no alternate form of the method; straightforward which version of the method you called. Example of final class: System Example of final class: System

33 June 17, 2008James Atlas - CISC37033 Explicit Object Casting Just like we can cast variables: Just like we can cast variables: double pi = 3.14; int i_pi = (int)pi; We can cast objects. We can cast objects. Rooster foghorn = (Rooster)chickens[1]; Use casting to use an object in its full capacity after its actual type (the derived class) has been forgotten Use casting to use an object in its full capacity after its actual type (the derived class) has been forgotten  The Rooster object is referred to only using a Chicken object variable

34 June 17, 2008James Atlas - CISC37034 Explicit Object Casting chickens[1] refers to an object variable to a Chicken object chickens[1] refers to an object variable to a Chicken object  We cannot access any of the Rooster-specific fields or methods using this object variable. We create a new object variable to a Rooster object We create a new object variable to a Rooster object  Using this variable will allow us to reference the Rooster-specific fields of our object… Rooster rooster = (Rooster) chickens[1];

35 June 17, 2008James Atlas - CISC37035 Object Casting We can do explicit type checking because chickens[1] refers to an object that is actually a Rooster object. We can do explicit type checking because chickens[1] refers to an object that is actually a Rooster object. For example, cannot do this with chickens[2] because it refers to a Hen (not Rooster) object For example, cannot do this with chickens[2] because it refers to a Hen (not Rooster) object We are “promising” the compiler that chickens[1] really refers to a Rooster object, although it is an object variable to a Chicken object. We are “promising” the compiler that chickens[1] really refers to a Rooster object, although it is an object variable to a Chicken object. If this is not the case, generates an exception. If this is not the case, generates an exception.  More about exceptions later. Rooster rooster = (Rooster) chickens[1]; // OK; chickens[1] refers to a Rooster object Rooster hen = (Rooster) chickens[2]; // ERROR; chickens[2] refers to a Hen object

36 June 17, 2008James Atlas - CISC37036 instanceof Operator Make sure such a cast will succeed before attempting it, using the instanceof operator: Make sure such a cast will succeed before attempting it, using the instanceof operator: operator returns a boolean operator returns a boolean  true if chickens[1] refers to an object of type Rooster  false otherwise if (chickens[1] instanceof Rooster) { rooster = (Rooster)chickens[1]; }

37 June 17, 2008James Atlas - CISC37037 Summary of Inheritance Place common operations & fields in the superclass. Place common operations & fields in the superclass.  Remove repetitive code by modeling the “is-a” hierarchy  Move “common denominator” code up the inheritance chain Protected fields are generally not a good idea. Protected fields are generally not a good idea. Don’t use inheritance unless all inherited methods make sense Don’t use inheritance unless all inherited methods make sense Use polymorphism. Use polymorphism.

38 June 17, 2008James Atlas - CISC37038 Real-world Example of Inheritance java.awt.Component   A base class representing a component in the Java Abstract Windowing Toolkit (GUI component)   Fields for background, foreground, height, width, visibility   Common code for resizing   Each implementation overrides the paint() method to provide specific drawing functionality javax.swing.plaf.basic.BasicArrowButton   Draws a triangular arrow in the paint() method

39 June 17, 2008James Atlas - CISC37039 Wrapper Classes Wrapper class for each primitive type Wrapper class for each primitive type Sometimes need an instance of an Object Sometimes need an instance of an Object  To use to store in HashMaps and other collections Include the functionality of parsing their respective data types. Include the functionality of parsing their respective data types. int x = 10; Integer y = new Integer(10);

40 June 17, 2008James Atlas - CISC37040 Wrapper Classes Autoboxing – automatically create a wrapper object Autoboxing – automatically create a wrapper object // implicitly 11 converted to // new Integer(11); Integer y = 11; Autounboxing – automatically extract a primitive type Autounboxing – automatically extract a primitive type Integer x = new Integer(11); int y = x.intValue(); int z = x; // implicitly, x is x.intValue();

41 June 17, 2008James Atlas - CISC37041 Packages Hierarchical structure of Java classes Hierarchical structure of Java classes  Directories of directories Use import to access packages Use import to access packages java net lang util Object Date Fully qualified name: java.util.Date

42 June 17, 2008James Atlas - CISC37042 Enum Pattern // int Enum Pattern - pre Java 1.5 public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; public static final int SEASON_SUMMER = 2; public static final int SEASON_FALL = 3; Problems with this implementation?

43 June 17, 2008James Atlas - CISC37043 Enum Pattern // int Enum Pattern - pre Java 1.5 public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; public static final int SEASON_SUMMER = 2; public static final int SEASON_FALL = 3; Problems with this implementation? Not typesafe Not typesafe No namespace No namespace Brittleness - requires recompilation of clients Brittleness - requires recompilation of clients Printed values uninformative Printed values uninformative

44 June 17, 2008James Atlas - CISC37044 Enum Pattern - Java 1.5+ // Enum Pattern - Java 1.5+ public enum Season { WINTER, SPRING, SUMMER, FALL }... public double getAverageTemperature(Season season) { switch(season) { case WINTER: case WINTER: return 15.0; return 15.0;......}}

45 June 17, 2008James Atlas - CISC37045 Exercise - Building A Casino


Download ppt "1 CISC370: Inheritance James Atlas. June 17, 2008James Atlas - CISC3702 Questions? Assignment 1 Assignment 1 Review Review."

Similar presentations


Ads by Google