1 / 0

Inheritance, Abstract Classes, Interface and Polymorphism

Inheritance, Abstract Classes, Interface and Polymorphism. Objectives. Understand class hierarchies and polymorphism Learn about abstract classes Learn the syntax for calling superclass’s constructors and methods. Understand interfaces Deriving new classes from existing classes

dianne
Download Presentation

Inheritance, Abstract Classes, Interface 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. Inheritance, Abstract Classes, Interface and Polymorphism

  2. Objectives Understand class hierarchies and polymorphism Learn about abstract classes Learn the syntax for calling superclass’s constructors and methods Understand interfaces Deriving new classes from existing classes The protected modifier Indirect visibility of inherited members Designing for inheritance
  3. Inheritance Classes are the blueprints and objects are the houses. Inheritance – lets say you want to keep the same basic features of a blueprint but want to change it a little and create a new blueprint by using the old and adding to it. This can thought of as inheritance. Inheritance takes one class and adds to another class by using the keyword extends. Inheritance – is how a new class is created from an existing class. The main purpose of inheritance is to reuse existing software making it easier, cheaper and using already tested code.
  4. Inheritance Inherited variables and methods can be used in the derived class as if they had been declared locally. Inheritance creates an “is-a” relationship between all parent and child classes.
  5. Inheritance The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined by the parent class
  6. “is – a” relationship example Lets say you have a class called Mammal. Mammal will be the parent or super class. The Mammal classes will contain all general methods and variables that all mammals has. Now let say you have a Class Horse. A Horse “is – a” Mammal. So since Horse is a Mammal, not only will Horse contain all the features of Mammal, since a Horse is a mammal, but it will also contain more specific methods and variable that only a horse has that other mammals may or may not have. Horse will be the subclass or child class.
  7. Keyword “extend” We use the keyword extend in the child class to inherit the parent’s class methods and variables.
  8. Example public class Book{ public int pages = 1500; public void pageMessage(){ System.out.println(“Number of pages” + pages); } } public class Dictionary extends Book{ private int definitions = 525000; public void definitionMessage(){ System.out.println(“Number of def “ + definitions); System.out.println(Definition per page” + definition/pages);} public class Word{ public static void main(Strings[] args){ Dictionary webster = new Dictionary(); webster.pageMessage(); webster.definitionMessage(); } } Output: Number of pages: 1500 Number of def 52500 Definition per page 35
  9. Graphical representation of inheritance Arrow always points from the child to the parent Mammal Book Horse Dictionary
  10. Inheritance Facts Not all variables and methods are inherited. The only variables and methods that are inherited are those that are declared as public in the parent class. The child class does not inherit the methods or variables declared as private. Constructors are not inherited in by the child class even though it is declared public.
  11. Rules of inheritance By the constructor not being inherited, breaks the rule of inheritance. This is an exception to the rule that all public methods and variables are inherited. Remember that constructors are declare as public. Encapsulation – By declaring variables public breaks the rule of encapsulation and therefore all variables should be declared private and use methods to change and access variables.
  12. Inheritance Superclass (Base class) Inheritance represents the IS-A relationship between objects: an object of a subclass IS-A(n) object of the superclass. Subclass extendsSuperclass Subclass (Derived class)
  13. Single inheritance Java only allows single inheritance. This term means that a child class can have only one parent. ** Other languages allow multiple inheritance. Can be difficult.
  14. Multiple Inheritance Java supports single inheritance, meaning that a derived class can have only one parent class Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents Collisions, such as the same variable name in two parents, have to be resolved Java does not support multiple inheritance In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead
  15. Super Super can be used in a class to refer to its parent class. A parent’s constructor can be invoked using the super reference. Super also allows us to reference members of the parent class.
  16. Super() The first line of a constructor uses the super reference of the parent class. This way the parent class always initializes its variables before the child class constructor begins to execute.
  17. Overriding Methods What happens if a child and parent class share the same method name and signature? The child method will override the parent’s method that is inherited.
  18. Class Hierarchies A child class can be a parent of its own child class. Common features should be kept as high in the hierarchy as possible. Example: Animal Bird Parrot
  19. Class Hierarchy Always use an is-a relationship The inheritance goes all the way down a hierarchy That is, a parent passes along a trait to a child, and the child class passes it long to its children, and so on.
  20. ToedInWalker CharlieChaplin Class Hierarchies Using inheritance, a programmer can define a hierarchy of classes. Biped Dancer Walker Hopper
  21. Biped Constructor Accessors turnLeft turnRight turnAround draw Hopper Constructor firstStep nextStep stop distanceTraveled Walker Constructor firstStep nextStep stop distanceTraveled Class Hierarchies (cont’d) Help reduce duplication of code by factoring out common code from similar classes into a common superclass.
  22. Class Hierarchies (cont’d) Help reduce duplication of code by letting you write more general methods in client classes. Works for either Walker or Hopper due to polymorphism public void moveAcross (Walker creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); } public void moveAcross (Hopper creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); } public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); }
  23. Business RetailBusiness ServiceBusiness KMart Macys Kinkos Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy
  24. Class Hierarchies Two children of the same parent are called siblings Common features should be put as high in the hierarchy as is reasonable An inherited member is passed continually down the line Therefore, a child class inherits from all its ancestor classes There is no single class hierarchy that is appropriate for all situations
  25. Polymorphism Is an OOP property in which objects have the ability to assume different types. Based on inheritance Since a subclass is derived from the superclass, a superclass object can reference an object of the subclass. Example: Circle wafer; Disk cookie = new Disk(2,0.5) wafer = cookie; //wafer references cookie Circle Disk
  26. Polymorphism In the last example, the wafer object, declared a Circle, is polymorphic, as demonstrated in the statement wafer = cookie where wafer assumes the form of cookie, a Disk object.
  27. Polymorphism What happens when the referenced object runs an overridden method? Which method runs?? If Disk overrides toString() & equals() from the parent class Circle, the Disk toString() method would run even though wafer is a Circle object. Example: System.out.println(wafer); // Disk toString() runs
  28. Polymorphism Ensures that the correct method is called for an object of a specific type, even when that object is disguised as a reference to a more generic type, that is, the type of the object’s superclass or some ancestor higher up the inheritance line. Once you define a common superclass, polymorphism is just there  no need to do anything special.
  29. Polymorphism (cont’d) The actual parameter passed to this method can be a Walker, a Hopper, etc.  any subclass of Biped. public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled () < distance) creature.nextStep(); creature.stop(); } Correct methods will be called automatically for any specific type of creature: Walker’s methods for Walker, Hopper’s for Hopper, etc.
  30. Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared the type of a reference variable cannot be changed. The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object. A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.
  31. Example: public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{} Now the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example: A Deer IS-A Animal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object When we apply the reference variable facts to a Deer object reference, the following declarations are legal: Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d; All the reference variables d,a,v,o refer to the same Deer object in the heap.
  32. Abstract Classes Some of the methods in a class can be declared abstract and left with only signatures defined A class with one or more abstract methods must be declared abstract public abstract class Biped { ... public abstract void firstStep(); public abstract void nextStep(); public abstract void stop(); ... public void draw(Graphics g) { ... } } Abstract methods
  33. Abstract Classes (cont’d) Abstract classes serve as common superclasses for more specific classes An abstract method provides an opportunity for the compiler to do additional error checking Abstract classes and methods are needed for polymorphism to work Abstract classes are closer to the root of the hierarchy; they describe more abstract objects
  34. Abstract Classes (cont’d) Java does not allow us to instantiate (that is, create objects of) abstract classes Still, an abstract class can have constructors  they can be called from constructors of subclasses A class with no abstract methods is called concrete
  35. Calling Superclass’s Constructors Biped Walker public class Walker extends Biped { // Constructor public Walker(int x, int y, Image leftPic, Image rightPic) { super(x, y, leftPic, rightPic); ... } } Calls Biped’s constructor The number / types of parameters passed to super must match parameters of one of the superclass’s constructors. If present, must be the first statement
  36. Calling Superclass’s Constructors (cont’d) One of the superclass’s constructors is always called, but you don’t have to have an explicit super statement. If there is no explicit call to super, then superclass’s no-args constructor is called by default. Must be defined then. If not defined  syntax error: cannot find symbol : constructor ...
  37. Calling Superclass’s Constructors (cont’d) Superclass’s constructor calls its superclass’s constructor, and so on, all the way up to Object’s constructor. Object super( ) Biped super(...) Walker
  38. Calling Superclass’s Methods Walker CharlieChaplin public class CharlieChaplin extends Walker { ... public void nextStep () { turnFeetIn(); super.nextStep(); turnFeetOut(); } ... } Calls Walker’s nextStep super.someMethod refers to someMethod in the nearest class, up the inheritance line, where someMethod is defined.
  39. Interfaces DanceFloor Aerobics Interface DanceGroup Waltz ControlPanel Rumba Dance Band Cha-Cha-Cha Dancer Salsa
  40. Interfaces (cont’d) An interface in Java is like an abstract class, but it does not have any fields or constructors, and all its methods are abstract. “public abstract” is not written because all the methods are public abstract. public interface Dance { DanceStep getStep (int i); int getTempo (); int getBeat (int i); }
  41. Interfaces (cont’d) We must “officially” state that a class implements an interface. A concrete class that implements an interface must supply all the methods of that interface. public class Waltz implements Dance { ... // Methods: public DanceStepgetStep (inti) { ... } public intgetTempo () { return 750; } public intgetBeat (inti) { ... } ... }
  42. Interfaces (cont’d) A class can implement several interfaces. Like an abstract class, an interface supplies a secondary data type to objects of a class that implements that interface. You can declare variables and parameters of an interface type. Polymorphism fully applies to objects disguised as interface types. Dance d = new Waltz( );
  43. Interfaces (cont’d) public interface Edible { String getFoodGroup(); int getCaloriesPerServing(); } public class Pancake implements Edible { ... } public class Breakfast { private int myTotalCalories = 0; ... public void eat (Edible obj, int servings) { myTotalCalories += obj.getCaloriesPerServing () * servings; } ... } Polymorphism: the correct method is called for any specific type of Edible,e.g., a Pancake
  44. A superclass provides a secondary data type to objects of its subclasses. An abstract class cannot be instantiated. An interface provides a secondary data type to objects of classes that implement that interface. An interface cannot be instantiated. Classes Interfaces Similarities
  45. A concrete subclass of an abstract class must define all the inherited abstract methods. A class can extend another class. A subclass can add methods and override some of its superclass’s methods. A concrete class that implements an interface must define all the methods specified by the interface. An interface can extend another interface (called its superinterface) by adding declarations of abstract methods. Classes Interfaces Similarities
  46. A class can extend only one class. A class can have fields. A class defines its own constructors (or gets a default constructor). A class can implement any number of interfaces. An interface cannot have fields (except, possibly, some public static final constants). An interface has no constructors. Classes Interfaces Differences
  47. A concrete class has all its methods defined. An abstract class usually has one or more abstract methods. Every class is a part of a hierarchy of classes with Object at the top. All methods declared in an interface are abstract. An interface may belong to a small hierarchy of interfaces, but this is not as common. Classes Interfaces Differences
  48. DanceStudio
  49. The protected Modifier Visibility modifiers affect the way that class members can be used in a child class Variables and methods declared with private visibility cannot be referenced by name in a child class They can be referenced in the child class if they are declared with public visibility -- but public variables violate the principle of encapsulation There is a third visibility modifier that helps in inheritance situations: protected
  50. The protected Modifier The protected modifier allows a child class to reference a variable or method directly in the child class It provides more encapsulation than public visibility, but is not as tightly encapsulated as private visibility A protected variable is visible to any class in the same package as the parent class Protected variables and methods can be shown with a # symbol preceding them in UML diagrams
  51. Book # pages : int + pageMessage() : void Words Dictionary - definitions : int + main (args : String[]) : void + definitionMessage() : void Class Diagram for Words
  52. The super Reference Constructors are not inherited, even though they have public visibility Yet we often want to use the parent's constructor to set up the "parent's part" of the object The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor
  53. The super Reference A child’s constructor is responsible for calling the parent’s constructor The first line of a child’s constructor should use the super reference to call the parent’s constructor The super reference can also be used to reference other variables and methods defined in the parent’s class
  54. Overriding Methods A child class can override the definition of an inherited method in favor of its own The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked
  55. Overriding A method in the parent class can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden The concept of overriding can be applied to data and is called shadowing variables Shadowing variables should be avoided because it tends to cause unnecessarily confusing code
  56. Overloading vs. Overriding Overloading deals with multiple methods with the same name in the same class, but with different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading lets you define a similar operation in different ways for different parameters Overriding lets you define a similar operation in different ways for different object types
  57. Class Object In Java every class by default extends a library class Object (from java.lang) Object is a concrete class Methods redefined (overridden) as necessary public class Object { public String toString {...} public boolean equals (Object other) {... } public int hashCode() { ... } // a few other methods ... }
  58. The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies
  59. The Object Class The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we define the toString method, we are actually overriding an inherited definition The toString method in the Object class is defined to return a string that contains the name of the object’s class along with some other information
  60. The Object Class The equals method of the Object class returns true if two references are aliases We can override equals in any class to define equality in some more appropriate way As we've seen, the String class defines the equals method to return true if two String objects contain the same characters The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version
  61. Abstract Classes An abstract class is a placeholder in a class hierarchy that represents a generic concept An abstract class cannot be instantiated We use the modifier abstract on the class header to declare a class as abstract: public abstract class Product { // contents }
  62. Abstract Classes An abstract class often contains abstract methods with no definitions (like an interface) Unlike an interface, the abstract modifier must be applied to each abstract method Also, an abstract class typically contains non-abstract methods with full definitions A class declared as abstract does not have to contain abstract methods -- simply declaring it as abstract makes it so
  63. Abstract Classes The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract An abstract method cannot be defined as final or static The use of abstract classes is an important element of software design – it allows us to establish common elements in a hierarchy that are too generic to instantiate
  64. Interface Hierarchies Inheritance can be applied to interfaces as well as classes That is, one interface can be derived from another interface The child interface inherits all abstract methods of the parent A class implementing the child interface must define all methods from both the ancestor and child interfaces Note that class hierarchies and interface hierarchies are distinct (they do not overlap)
  65. Visibility Revisited It's important to understand one subtle issue related to inheritance and visibility All variables and methods of a parent class, even private members, are inherited by its children As we've mentioned, private members cannot be referenced by name in the child class However, private members inherited by child classes exist and can be referenced indirectly
  66. Visibility Revisited Because the parent can refer to the private member, the child can reference it indirectly using its parent's methods The super reference can be used to refer to the parent class, even if no object of the parent exists
  67. Designing for Inheritance As we've discussed, taking the time to create a good software design reaps long-term benefits Inheritance issues are an important part of an object-oriented design Properly designed inheritance relationships can contribute greatly to the elegance, maintainabilty, and reuse of the software Let's summarize some of the issues regarding inheritance that relate to a good software design
  68. Inheritance Design Issues Every derivation should be an is-a relationship Think about the potential future of a class hierarchy, and design classes to be reusable and flexible Find common characteristics of classes and push them as high in the class hierarchy as appropriate Override methods as appropriate to tailor or change the functionality of a child Add new variables to children, but don't redefine (shadow) inherited variables
  69. Inheritance Design Issues Allow each class to manage its own data; use the super reference to invoke the parent's constructor to set up its data Even if there are no current uses for them, override general methods such as toString and equals with appropriate definitions Use abstract classes to represent general concepts that lower classes have in common Use visibility modifiers carefully to provide needed access without violating encapsulation
  70. Restricting Inheritance The final modifier can be used to curtail inheritance If the final modifier is applied to a method, then that method cannot be overridden in any descendent classes If the final modifier is applied to an entire class, then that class cannot be used to derive any children at all Thus, an abstract class cannot be declared as final These are key design decisions, establishing that a method or class should be used as is
More Related