Chapter 11 Inheritance and Encapsulation and Polymorphism 1


























- Slides: 26

Chapter 11 Inheritance and Encapsulation and Polymorphism 1

Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: F Add new properties F Add new methods F Override the methods of the superclass 2

Superclasses and Subclasses Geometric. Object 1 Circle 4 Rectangle 1 Test. Circle. Rectangle Run 3

Are superclass’s Constructor Inherited? No. They are not inherited. They are invoked explicitly or implicitly. Explicitly using the super keyword. A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. They can only be invoked from the subclasses' constructors, using the keyword super. If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked. 4

Using the Keyword super The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: F To call a superclass constructor F To call a superclass method 5

CAUTION • You must use the keyword super to call the superclass constructor. Invoking a superclass constructor’s name in a subclass causes a syntax error. • Java requires that the statement that uses the keyword super appear first in the constructor. 6

Multiple Inheritance • A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. • Therefore following is illegal: 7

Multiple Inheritance • However, C++ provides the ability to do multiple inheritance. Multiple inheritance enables a derived class to inherit members from more than one parent. • To provide Multiple Inheritance functionality Java uses Interfaces. A class can implement one or more interfaces. 8

Overriding vs. Overloading 9

The to. String() method in Object The to. String() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object. Loan loan = new Loan(); System. out. println(loan. to. String()); The code displays something like Loan@15037 e 5. This message is not very helpful or informative. Usually you should override the to. String method so that it returns a digestible string representation of the object. 10

The instanceof Operator Use the instanceof operator to test whether an object is an instance of a class: Object my. Object = new Circle(); // Some lines of code /** Perform casting if my. Object is an instance of Circle */ if (my. Object instanceof Circle) { System. out. println("my. Object is instance of Circle"); . . . } 11

Encapsulation F encapsulation: Hiding implementation details from clients. – Encapsulation forces abstraction. u separates external view (behavior) from internal view (state) u protects the integrity of an object's data

Private fields A field that cannot be accessed from outside the class private type name; – Examples: private int id; private String name; F Client fields: code won't compile if it accesses private

Accessing private state

Accessing private state // A "read-only" access to the x field public int get. X() { return x; } // Allows clients to change the x field public void set. X(int new. X) { x = new. X; } – Client code will look more like this: System. out. println(p 1. get. X()); p 1. set. X(14);

Example: Point class // A Point object represents an (x, y) location. public class Point { private int x; private int y; public Point(int initial. X, int initial. Y) { x = initial. X; y = initial. Y; } public int get. X() { return x; } public int get. Y() { return y; } public double distance. From. Origin() { return Math. sqrt(x * x + y * y); } public void set. Location(int new. X, int new. Y) { x = new. X; y = new. Y; } } public void translate(int dx, int dy) { set. Location(x + dx, y + dy); }

Benefits of encapsulation F Abstraction F Protects between object and clients object from unwanted access – Example: Can't fraudulently increase an Account's balance. F Can constrain objects' state (invariants) – Example: Only allow Accounts with nonnegative balance. – Example: Only allow Dates with a month from 1 -12.

The Array. List Class You can create an array to store objects. But the array’s size is fixed once the array is created. Java provides the Array. List class that can be used to store an unlimited number of objects. 18

Array. List Example Test. Array. List Run 19

The protected Modifier F The protected modifier can be applied on data and methods in a class. A protected data or a protected method in a public class can be accessed by any class in the same package or its subclasses. F Cannot be accessed if the subclasses are in a different package. F private, default, protected, public 20

Accessibility Summary 21

Visibility Modifiers 22

NOTE the final modifier can also be used on local variables in a method. A final local variable is a constant inside a method. 23

The final Modifier F The final class cannot be extended: final class Math {. . . } F The final variable is a constant: final static double PI = 3. 14159; F The final method cannot be overridden by its subclasses. 24

Polymorphism F Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. F Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. F For example, think of a superclass called Animal that has a method called animal. Sound(). – Subclasses of Animals could be Pigs, Cats, Dogs, Birds – they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc. ): 25

Polymorphism class Animal { public void animal. Sound() { System. out. println("The animal makes a sound"); } } class Pig extends Animal { public void animal. Sound() { System. out. println("The pig says: wee"); } } Pig from Animal object class Dog extends Animal { public void animal. Sound() { System. out. println("The dog says: bow wow"); } } class My. Main. Class { public static void main(String[] args) { Animal my. Animal = new Animal(); // Create a Animal object Animal my. Pig = new Pig(); // Create a Pig object Animal my. Dog = new Dog(); // Create a Dog object my. Animal. animal. Sound(); my. Pig. animal. Sound(); my. Dog. animal. Sound(); } } Dog from Animal object 26