chapter 8 class inheritance and interfaces n.
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 8 Class Inheritance and Interfaces PowerPoint Presentation
Download Presentation
Chapter 8 Class Inheritance and Interfaces

Chapter 8 Class Inheritance and Interfaces

181 Views Download Presentation
Download Presentation

Chapter 8 Class Inheritance and Interfaces

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Chapter 8 Class Inheritance and Interfaces • Superclasses and Subclasses • Keywords: super • Overriding methods • The Object Class • Modifiers: protected, final and abstract • Abstract classes • Polymorphism and Object Casting • Interfaces • Inner Classes

  2. Superclasses and Subclasses UML Diagram

  3. Creating a Subclass Creating a subclass extends properties and methods from the superclass. You can also: • Add new properties • Add new methods • Override the methods of the superclass Cylinder Class

  4. Example 8.1Testing Inheritance • Objective: Create a Cylinder object and explore the relationship between the Cylinder and Circle classes. TestCylinder Run

  5. 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: • To call a superclass constructor • To call a superclass method

  6. 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.

  7. NOTE 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 default constructor is automatically invoked.

  8. Example on Calling Superclass’s Constructors public class C1 extends C2 { public static void main(String[] args) { new C1(); } public C1() { System.out.println("C1's default constructor is invoked"); } } class C2 extends C3 { public C2() { System.out.println("C2's default constructor is invoked"); } } class C3 { public C3() { System.out.println("C3's default constructor is invoked"); } }

  9. NOTE If a superclass defines constructors other than a default constructor, the subclass cannot use the default constructor of the superclass, because in this case the superclass does not have a default constructor.

  10. Example on the Impact of a Superclass with no Default Constructor public class A extends B { } class B { public B(String name) { System.out.println("B's constructor is invoked"); } }

  11. Example 8.2 Overriding Methods in the Superclass The Cylinder class overrides the findArea() method defined in the Circle class. Cylinder TestOverrideMethods Run

  12. NOTE An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated.

  13. NOTE Like an instance method, a static method can be inherited. However, a static method cannot be overridden. If a method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden.

  14. The Object Class • The Object class is the root of all Java classes. • The equals() method compares thecontents of two objects. • The toString() method returns a string representation of the object. • The clone() method copy objects

  15. The Object Class, cont. The equals() method compares thecontents of two objects. The default implementation of the equals method in the Object class is as follows: public boolean equals(Object obj) { return (this == obj); }

  16. NOTE The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. The equals method is intended to test whether two objects have the same contents, provided that the method is modified in the defining class of the objects. The == operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object.

  17. The Object Class, cont. • The toString() 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. The clone() method copy objects

  18. The Object Class, cont. To create a new object with separate memory space, you need to use the clone() method, as follows: newObject = someObject.clone(); NOTE: Not all objects can be cloned. For an object to be cloneable, its class must implement the java.lang.Cloneable interface. Interfaces are introduced in the section "Interfaces," in this chapter.

  19. The protected Modifier • 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, even if the subclasses are in a different package.

  20. The protected Modifier, cont.

  21. NOTE A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass.

  22. NOTE The modifiers are used on classes and class members (data and methods), except that 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 • The final class cannot be extended: final class Math { ... } • The final variable is a constant: final static double PI = 3.14159; • The final method cannot bemodified by its subclasses.

  24. The abstract Modifier • The abstract class • Cannot be instantiated • Should be extended and implemented in subclasses • The abstract method • Method signature withoutimplementation

  25. Abstract Classes GeometricObject Circle Cylinder Rectangle

  26. NOTE An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be declared abstract. In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass.

  27. NOTE An abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses. For instance, the constructors of GeometricObject are invoked in the Circle class and the Rectangle class.

  28. NOTE A class that contains abstract methods must be abstract. However, it is possible to declare an abstract class that contains no abstract methods. In this case, you cannot create instances of the class using the new operator. This class is used as a base class for defining a new subclass.

  29. NOTE A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract.

  30. NOTE A subclass can override a method from its superclass to declare it abstract. This is rare, but useful when the implementation of the method in the superclass becomes invalid in the subclass. In this case, the subclass must be declared abstract.

  31. NOTE You cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type. Therefore, the following statement, which creates an array whose elements are of GeometricObject type, is correct. GeometricObject[] geo = new GeometricObject[10];

  32. NOTE Cylinder inherits the findPerimeter method from Circle. If you invoke this method on a Cylinder object, the perimeter of a circle is returned. This method is not useful for Cylinder objects. It would be nice to remove or disable it from Cylinder, but there is no good way to get rid of this method in a subclass once it is defined as public in its superclass. If you define the findPerimeter method abstract in the Cylinder class, then the Cylinder class must be declared abstract.

  33. Polymorphism, Dynamic Binding and Generic Programming Polymorphism refers to the ability to determine at runtime which code to run, given multiple methods with the same name in different classes in an inheritance hierarchy. This ability is also known as dynamic binding. Polymorphism allows methods to be used generically for a wide range of object arguments. This is known as generic programming.

  34. Example 8.3 Testing Polymorphism • Objective: This example creates two geometric objects: a circle, and a rectangle, invokes the equalArea method to check if the two objects have equal area, and invokes the displayGeometricObject method to display the objects. TestPolymorphism Run

  35. NOTE Matching a method signature and binding a method implementation are two issues. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time. A method may be implemented in several subclasses. The JVM dynamically binds the implementation of the method at runtime.

  36. Casting Objects It is always possible to convert a subclass to a superclass. For this reason, explicit casting can be omitted. For example, Circle myCircle = myCylinder is equivalent to Circle myCircle = (Circle)myCylinder;

  37. Casting fromSuperclass to Subclass Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Cylinder myCylinder = (Cylinder)myCircle;

  38. The instanceof Operator Use the instanceof operator to test whether an object is an instance of a class: Circle myCircle = new Circle(); if (myCircle instanceof Cylinder) { Cylinder myCylinder = (Cylinder)myCircle; ... }

  39. Example 8.4Casting Objects This example creates two geometric objects: a circle, and a cylinder, invokes the displayGeometricObject method to display the objects. The displayGeometricObject displays the area and perimeter if the object is a circle, and displays area and volume if the object is a cylinder. TestCasting Run

  40. Interfaces • What Is an Interface? • Creating an Interface • Implementing an Interface • What is Marker Interface?

  41. Creating an Interface modifier interface InterfaceName { constants declarations; methods signatures; }

  42. Example of Creating an Interface // This interface is defined in // java.lang package public interface Comparable { public int compareTo(Object o); }

  43. Generic max Method public class Max { // Return the maximum between two objects public static Comparable max (Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } }

  44. Example 8.5 Using Interfaces • Objective: Use the max method to find a find the maximum circle between two circles and a maximum cylinder between two cylinders.

  45. Example 8.5, cont. TestInterface Run

  46. Interfaces vs. Abstract Classes In an interface, the data must be constants; an abstract class can have all types of data. Each method in an interface has only a signature without implementation; an abstract class can have concrete methods. An abstract class must contain at least one abstract method or inherit from another abstract method.

  47. Interfaces vs. Abstract Classes, cont. Since all the methods defined in an interface are abstract methods, Java does not require you to put the abstract modifier in the methods in an interface, but you must put the abstract modifier before an abstract method in an abstract class.

  48. Interfaces vs. Abstract Classes, cont.

  49. The Cloneable Interfaces Marker Interface: An empty interface. A marker interface does not contain constants or methods, but it has a special meaning to the Java system. The Java system requires a class to implement the Cloneable interface to become cloneable. public interface Cloneable { }

  50. Example 8.6 Cloning Objects • Objective: uses the Cloneable interface to mark classes cloneable and uses the clone method to copy objects. TestCloneable Run