1 / 67

Inheritance and Polymorphism

Object-Oriented Programming in Java. Inheritance and Polymorphism. Contents. Inheritance in Java Inheriting Classes The super Reference Overriding Methods Polymorphism The instanceof Operator final Methods and Classes. 2. Contents (2). Abstract Classes Abstract Methods Interfaces

shayla
Download Presentation

Inheritance and Polymorphism

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object-Oriented Programming in Java Inheritance and Polymorphism

  2. Contents • Inheritance in Java • Inheriting Classes • The super Reference • Overriding Methods • Polymorphism • The instanceof Operator • final Methods and Classes 2

  3. Contents (2) • Abstract Classes • Abstract Methods • Interfaces • Defining Interfaces • Implementing Interfaces • Using Interfaces (Demo) 3

  4. Access Modifiers public, private, protected, default (package)

  5. Access Modifiers • The most common modifiers are the access modifiers: • public • private • protected • (default) • Access modifiers control which classes may use a member 5

  6. Access Modifiers Rules • The variables that you declare and use within a class’s methods may not have access modifiers • The only access modifier permitted to non-inner classes is public • A member may have at most one access modifier 6

  7. public • The most generous access modifier is public • A public class, variable, or method may be used in any Java program without restriction • Any public method may be overridden by any subclass 7

  8. private • The least generous access modifier is private • Top-level (that is, not inner) classes may not be declared private • A private variable or method may be used only by an instance of the class that declares the variable or method 8

  9. protected • Only variables and methods may be declared protected • A protected member of a class is available to all classes in the same package, just like a default member • A protected member of a class can be available in certain limited ways to all subclasses of the class that owns the protected member. It is visible in subclasses in different packages too. 9

  10. (default) • Default is the name of the access of classes, variables, and methods if you don’t specify an access modifier • A class’s data and methods may be default, as well as the class itself • A class’s default members are accessible to any class in the same package as the class in question • A default method may be overridden by any subclass that is in the same package as the superclass 10

  11. Packages

  12. What Are Java Packages? • A package is a container of classes that are logically related • A package consists of all the Java classes within a directory on the file system • Package names and used within a JRE to manage the uniqueness of identifiers • They segment related parts of complex applications into manageable parts

  13. Grouping Classes in a Package • Include the package keyword followed by one or more names separated by dots at the top of the Java source file • If omitted the compiler places the class in the default “unnamed” package package utils; public class MathUtils { ... } 13

  14. Grouping Classes in a Package • To run a main() method in a packaged class requires: • The CLASSPATH to contain the directory having the root name of the package tree • The class name must be qualified by itspackage name java –cp . myPackage.MainClass 14

  15. The CLASSPATH with Packages • Includes the directory containing the top level of the package tree .class location Package name CLASSPATH C:\>set CLASSPATH=E:\Curriculum\courses\java\practices\les06 15

  16. Importing Packages • To use a class defined in other package (not in current) you should do either: • Import the class or all classes in the package: • Use the full name of the class: import utils.MathUtils; ... int sq = MathUtils.FastCalculateSqrt(12345); int sq = utils.MathUtils.FastCalculateSqrt(12345); 16

  17. Inheritance and Polymorphism Code Reuse Techniques

  18. Key Object-Oriented Components • Inheritance • Constructors referenced by subclass • Polymorphism • Inheritance is an OO fundamental Superclass InventoryItem Subclasses Movie Game Book

  19. Example of Inheritance • The InventoryItem class defines methods and variables • Movie extends InventoryItem and can: • Add new variables • Add new methods • Override methods in InventoryItem class InventoryItem Movie

  20. Specifying Inheritance in Java • Inheritance is achieved by specifying which superclass the subclass extends • Movie inherits all the variables and methods of InventoryItem public class InventoryItem { … } public class Movie extends InventoryItem { … }

  21. What Does a Subclass Object Look Like? • A subclass inherits all the instance variables of its superclass public class InventoryItem { private float price; private String condition; … } Movie price condition public class Movie extends InventoryItem { private String title; private int length; … } title length

  22. Default Initialization • What happens when a subclass object is created? • If no constructors are defined: • First, the default parameterless constructor is called in the superclass • Then, the default parameterless constructor is called in the subclass Movie movie1 = new Movie(); Movie price condition title length

  23. The super Reference • Refers to the base class • Is useful for calling base class constructors • Must be the first line in the derived class constructor • Can be used to call any base class methods public class Movie extends InventoryItem { public Movie() { super("Matrix 8"); } }

  24. The super Reference Example public class InventoryItem { InventoryItem(String cond) { System.out.println("InventoryItem"); … } } class Movie extends InventoryItem { Movie(String title) { super(title); … System.out.println("Movie"); } } Base class constructor Calls base class constructor

  25. Using Superclass Constructors • Use super() to call a superclass constructor: public class InventoryItem { InventoryItem(float p, String cond) { price = p; condition = cond; } … public class Movie extends InventoryItem { Movie(String t, float p, String cond) { super(p, cond); title = t; } …

  26. Specifying Additional Methods • The superclass defines methods for all types of InventoryItem • The subclass can specify additional methods that are specific to Movie public class InventoryItem { public float calcDeposit()… public String calcDateDue()… … public class Movie extends InventoryItem { public void getTitle()… public String getLength()…

  27. Overriding Superclass Methods • A subclass inherits all the methods of its superclass • The subclass can override a method with its own specialized version • Must have the same signature and semantics as the superclass method • In Java all methods are virtual (unless declared as final) • This forces the late binding mechanism on each method call

  28. Overriding Superclass Methods – Example public class InventoryItem { … public float calcDeposit(int custId) { return itemDeposit; } } public class Movie extends InventoryItem { … public float calcDeposit(int custId) { if (specialCustomer(custId) { return itemDeposit / 2; } else { return itemDeposit; } } }

  29. Invoking Superclass Methods • If a subclass overrides a method, it can still call the original superclass method • Use super.method() to call a superclass method from the subclass public class InventoryItem { public float calcDeposit(int custId) { if … return 33.00; } public class Movie extends InventoryItem { public float calcDeposit(int custId) { itemDeposit = super.calcDeposit(custId); return (itemDeposit + vcrDeposit); }

  30. Treating a Subclass as Its Superclass • A Java object instance of a subclass is plug compatible with its superclass definition • You can assign a subclass object to a reference declared with the superclass: • The compiler treats the object via its reference, that is, in terms of its superclass definition • The JVM creates a subclass object, executing subclass methods, if overridden public static void main(String[] args) { InventoryItem item = new Movie(); double deposit = item.calcDeposit(); } 30

  31. Acme Video and Polymorphism • Acme Video started renting only videos • Acme Video added games and VCRs • What’s next? • Polymorphism solves the problem

  32. How It Works InventoryItem calcDeposit(){…} Movie VCR calcDeposit(){…} calcDeposit(){…} ShoppingBasket void addItem(InventoryItem item) { // this method is called each time // the clerk scans in a new item float deposit = item.calcDeposit(); … }

  33. Using the instanceof Operator • The true type of an object can be determined by using an instanceof operator • An object reference can be downcast to the correct type, if needed public void aMethod(InventoryItem i) { … if (i instanceof Movie) ((Movie)i).playTestTape(); }

  34. Limiting Methods and Classes with final • A method can be marked as final to prevent it from being overridden • A whole class can be marked as final to prevent it from being extended public final boolean checkPassword(String p) { … } public final class Color { … }

  35. When to Use Inheritance? • Inheritance should be used only for “is a kind of” relationships: • It must always be possible to substitute a subclass object for a superclass object • All methods in the superclass should make sense in the subclass • Inheritance for short-term convenience leads to problems in the future

  36. Abstract Classes and Interfaces

  37. Defining Abstract Classes • Abstract classes model abstract concepts from the real world • Cannot be instantiated directly • Should be subclasses to be instantiated • Abstract methods must be implemented by subclasses Abstract superclass InventoryItem Concrete subclasses Movie VCR

  38. Creating Abstract Classesin Java • Use the abstract keyword to declare a class as abstract public abstract class InventoryItem { private float price; public boolean isRentable()… } public class Movie extends InventoryItem { private String title; public int getLength()… public class Vcr extends InventoryItem { private int serialNbr; public void setTimer()…

  39. What Are Abstract Methods? • An abstract method: • Is an implementation placeholder • Is part of an abstract class • Must be overridden by a concrete subclass • Each concrete subclass can implement the method differently

  40. Defining Abstract Methodsin Java • Use the abstract keyword to declare a method as abstract: • Provide the method signature only • The class must also be abstract • Why is this useful? • Declare the structure of a class without providing complete implementation of every method public abstract class InventoryItem { public abstract boolean isRentable(); …

  41. Defining and Using Interfaces • An interface is like a fully abstract class: • All of its methods are abstract • All variables are public static final • An interface lists a set of method signatures, without any code details • A class that implements the interface must provide code details for all the methods of the interface • A class can implement many interfaces but can extend only one class

  42. Example of Interfaces • Interfaces describe an aspect of behavior that different classes require • For example, classes that can be steered support the “steerable” interface • Classes can be unrelated Steerable Nonsteerable

  43. Creating an Interface • Use interface keyword • All methods public abstract • All variables public static final public interface Steerable { int MAXTURN_DEGREES = 45; void turnLeft(int deg); void turnRight(int deg); }

  44. Implementing an Interface • Use implements keyword public class Yacht extends Boatimplements Steerable public void turnLeft(int deg) {…} public void turnRight(int deg) {…} }

  45. Sort: A Real-World Example • Is used by a number of unrelated classes • Contains a known set of methods • Is needed to sort any type of objects • Uses comparison rules known only to the sortable object • Supports good code reuse

  46. Overview of the Classes • Created by the sort expert: • Created by the movie expert: public interface Sortable public class Sort public class Movie implements Sortable public class MovieSortApplication

  47. How the Sort Works? MyApplication sortObjects() returns the sorted list MyApplication passes an array of movies to Sort.sortObjects() 4 1 Sort The movie returns the result of the comparison sortObjects() asks a movie to compare itself with another movie 2 3 Movie

  48. The Sortable Interface • Specifies the compare() method public interface Sortable { // compare(): Compare this object // to another object // Returns: // 0 if this object is equal to obj2 // a value < 0 if this object < obj2 // a value > 0 if this object > obj2 int compare(Object obj2); }

  49. The Sort Class • Implements sorting functionality: the method sortObjects() public class Sort { public static void sortObjects(Sortable[] items) { // Perform "Bubble sort" algorithm for (int i = 1; i < items.length; i++) { for (int j = 0; j < items.length-1; j++) { if (items[j].compare(items[j+1]) > 0) { Sortable tempItem = items[j+1]; items[j+1] = items[j]; items[j] = tempItem; } } } } }

  50. The Movie Class • Implements Sortable public class Movie extends InventoryItemimplements Sortable { private String title; public int compare(Object movie2) { String title1 = this.title; String title2 = ((Movie)movie2).getTitle(); return(title1.compareTo(title2)); } }

More Related