Download presentation
Presentation is loading. Please wait.
Published byAnnis Anderson Modified over 6 years ago
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 = ; 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
Subclass extends Superclass
Inheritance Superclass (Base class) Subclass extends Superclass Subclass (Derived class) A subclass inherits all the fields and methods of its superclass, but not constructors. Inheritance represents the IS-A relationship between objects: an object of a subclass IS-A(n) object of the superclass.
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
Class Hierarchies Using inheritance, a programmer can define a hierarchy of classes. Biped Walker Hopper Dancer The class Biped is a generic class that represents any kind of “creature” that moves on two legs. (The term biped comes from Latin: bi means “two,” and ped means “foot.”) ToedInWalker CharlieChaplin
21
Class Hierarchies (cont’d)
Help reduce duplication of code by factoring out common code from similar classes into a common superclass. Biped Constructor Accessors turnLeft turnRight turnAround draw Walker Constructor firstStep nextStep stop distanceTraveled Hopper Constructor firstStep nextStep stop distanceTraveled If two classes share a lot of code, it makes sense to define a common superclass and factor out common code into it.
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(); } (Hopper creature, int distance) public void moveAcross (Biped creature, int distance) { creature.firstStep(); while (creature.distanceTraveled() < distance) creature.nextStep(); creature.stop(); } So inheritance helps to eliminate duplicating code in two ways: (1) by factoring out common code and (2) by writing more general methods.
23
Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Business KMart Macys ServiceBusiness Kinkos RetailBusiness
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. Java implements polymorphism through a technique known as late (or dynamic) method binding: which method to call is defined at run time, not compile time. Each object holds a table of entry points to its methods, so each object itself knows exactly what to do when one of its methods is called.
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(); } We pass to a method a specific type of object. Inside the method the object is disguised as a more generic type, but “deep inside” it still “knows” what type of object it is. 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) { ... } } An abstract class can have fields, constructors, and regular methods. 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 Additional error checking: if a concrete (non-abstract) class extends an abstract class, it must override all of the abstract methods.
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 Superclass’s constructors are called using the keyword super, as discussed shortly.
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 In this example super passes “up” all the parameters received by Walker’s constructor. In general, this does not have to be the case. 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. This error message pops up unexpectedly and appears quite puzzling. 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( ) Superclass’s constructor is called to initialize superclass’s fields. Biped super(...) Walker
38
Calling Superclass’s Methods
Walker CharlieChaplin public class CharlieChaplin extends Walker { ... public void nextStep () turnFeetIn(); super.nextStep(); turnFeetOut(); } Here nextStep calls superclass’s nextStep, the same method that it overrides. This is common, but, in general, a method can explicitly call any method of the superclass. For example, nextStep could call super.stop(). 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 DanceGroup Waltz ControlPanel Dance
Rumba Band Cha-Cha-Cha In the computer world, the term interface refers to any mechanism that connects two devices or entities and defines the rules for their interaction. 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); } An interface can also have public static constants.
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 DanceStep getStep (int i) { ... } public int getTempo () { return 750; } public int getBeat (int i) { ... } } It is not sufficient to supply all the methods -- we must state “implements” in the class’s header. An abstract class can supply some of the interface’s methods, leaving others abstract.
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. The main advantage of interfaces over abstract classes is that a class can implement several interfaces but extend only one superclass. 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 Obviously an interface cannot help to factor out common code from several classes (because an interface does not have any executable code); but an interface can help to eliminate duplicate code by letting us write more general methods.
44
Classes Interfaces Similarities 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. A class in a hierarchy accumulates all the secondary data types of its ancestors, including all the interfaces that they implement.
45
Classes Interfaces Similarities 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. If a concrete class implements several interfaces, it must supply all of their methods.
46
Classes Interfaces A class can extend only one class.
Differences 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. Interfaces is Java’s response to “multiple inheritance.”
47
Classes Interfaces Differences 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.
48
Dance Studio Strategically positioned interfaces in this application add flexibility. For example, in Chapter 3 we were able to easily turn Dance Studio into First Steps by replacing a DanceGroup and Dancers with a WalkingGroup and Walkers (or a PacingGroup and Pacers).
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
Class Diagram for Words
Book # pages : int + pageMessage() : void Dictionary - definitions : int + definitionMessage() : void Words + main (args : String[]) : void
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 ... } Object’s toString returns a string that holds object’s class name and hex address in memory -- not very useful for most classes. For example, if we comment out for a moment the toString method in Fraction and execute System.out.println(new Fraction(2, 3)); we will see something like We need to override Object’s toString in our class if we want to convert our objects to strings in a meaningful way.
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.