470 likes | 555 Views
UFCE3T-15-M Object-oriented Design and Programming Block2: Inheritance, Polymorphism, Abstract Classes and Interfaces Jin Sa. Objectives. To understand the concept of inheritance. To develop a subclass from a superclass through inheritance.
E N D
UFCE3T-15-M Object-oriented Design and Programming Block2: Inheritance, Polymorphism, Abstract Classes and InterfacesJin Sa
Objectives • To understand the concept of inheritance. • To develop a subclass from a superclass through inheritance. • To invoke the superclass’s constructors and methods using the super keyword. • To override methods in the subclass. • To comprehend polymorphism. • To understand casting. • To restrict access to data and methods using the protected visibility modifier. • To understand the concepts of abstract classes and interfaces • To design and use abstract classes. • To declare interfaces to model weak inheritance relationships. • To know the similarities and differences between an abstract class and interface
Examples of Inheritance • Student.java • MScStudent.java • TestStudentHierarchy.java
Student class public class Student {private String name; Student(String nm ){ name=nm;}public String getName() { return name;}public String toString() { // return info about the object return name;} }
MScStudent class public class MScStudent extends Student { private String supervisor; MScStudent(String nm) {super(nm); } public void chooseSupervisor(String nm) { supervisor=nm; } public String toString(){ return (super.toString()+ "\n Supervisor is: "+supervisor); } }
TestStudentHierarchy class public class TestStudentHierarchy { public static void main(String [] args) { Student s1=new Student("jane"); MScStudent ms1 = new MScStudent("mike"); System.out.println(s1.toString()); System.out.println(ms1.toString()); s1=ms1; System.out.println(s1.toString()); //((MScStudent)s1).chooseSupervisor("jj"); System.out.println(s1.toString()); } }
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 See the MSc example.
Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: • Add new properties • Add new methods • Override the methods of the superclass
Overriding Methods in the Superclass • A subclass inherits methods from a superclass. • Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. • This is referred to as method overriding.
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.
The Object Class Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object.
The toString() method in Object 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. Circle c = new Circle(2.0); System.out.println(c.toString()); The code displays something like Circle@15037e5.This message is not very helpful or informative. Usually you should override the toString method so that it returns a digestible string representation of the object.
Object References and Class Hierarchy • In Java an object reference that is declared of a particular class can be used to refer to an object of any subclass. See the TestStudentHierarchy example. Student s1=new Student("jane"); MScStudent ms1 = new MScStudent("mike");… s1=ms1;//s1 points to an MScStudent System.out.println(s1.toString());
Polymorphism • Polymorphism means “many forms”. • s1 was a polymorphic reference. It can refer to different kinds of objects. • An example of polymorphism is the technique by which a reference that is used to invoke a method can actually invoke different methods at different times depending on what it is referring to at the time.
Polymorphism • In the TestStudetnHierarch example, the reference s1 uses the type of the object it points to determine which toString() method to use. If it is pointing to a Student, it uses the toString() method in the Student class; if it is pointing to an MScStudent, it uses the method defined in the MScStudent.
Casting Objects Casting can be used to convert an object of one class type to another within an inheritance hierarchy. In the statement s1=new MScStudent(“jane”); assigns the object new MscStudent() to a reference of the Student type. This statement is involves an implicit casting. This is legal because an instance of MScStudent is an instance of Student.
Casting Object Explicit casting must be used when casting an object from a superclass to a subclass. On the previous slide we have assigned an MScStudent to the reference s1. So let’s try s1.chooseSupervisor(“jj”); s1 is still a reference of type Student. Student does not have the method chooseSupervisor. So, we have to explicitly cast s1 to MScStudent. ((MScStudent)s1).chooseSupervisor(“jj”);
Example 8.1Demonstrating Polymorphism and Casting See the TestStudentHierarchy example.
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. • private, default, protected, public
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 beoverridden by its subclasses.
The equals Method 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); } public boolean equals(Object o) { if (o instanceof Circle) { return radius == ((Circle)o).radius; } else return false; } For example, the equals method is overridden in the Circle class.
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.
Abstract Methods and Classes • Consider an application that deals with different shapes, we may need to define a circle class, a square class and a triangle class etc. • All have some common features, e.g. colour, area • So we want to define a shape class which includes these common features. Circle, Square etc can inherit from Shape and add additional information.
Abstract Methods • How do we define findArea() of Shape? • Need to know what shape it is in order to know the formula. • Abstract methods provide “place holders” for methods that can sensibly mentioned at one level, but that are going to be implemented in a variety of ways in the subclasses.
Abstract Methods • In the Shape class, we know there is a common concept, findArea, but it does nto make sense to provide the detailled description. Hence we have the concept of Abstract Methods. • In Java, the syntax is public abstract double findArea();
Abstract Classes • An abstract class is any class with at least one abstract method. An abstract class cannot be used to declare objects any more. The presence of the abstract method means that it is incomplete.
The abstract Modifier • The abstract class • Cannot be instantiated • Should be extended and implemented in subclasses • The abstract method • Method signature withoutimplementation
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 Shape are invoked in the Circle class and the Square class.
NOTE 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.
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 Shape type, is correct. • Shape [] collection = new Shape[5]; • Each collection[i] can point to an instance of Square, Circle
Example 9.1 Using the Shape Class • Objective: This example creates two shape objects: a circle, and a square, check if the which object has the bigger area. • TestShapes.java
Interfaces An interface is a class like construct that contains only constants and abstract methods. In many ways, an interface is similar to an abstract class, but an abstract class can contain variables and concrete methods as well as constants and abstract methods. To define an interface, Java uses the following syntax to declare an interface: public interface InterfaceName { constant declarations; method signatures; }
Implementing Interfaces • A class implements an interface by providing method implementations for each of the methods in the interface declaration. • Classes implement an interface use the implements keyword. Class classname implements interfacename { attributes and methods for this class implementation of methods named in the interfacce }
Interface example public interface ComfyLife { void havePlentyFood(); void haveGoodTime(); }
Implementing Interfaces • Consider the Student class described in the case study in block1 public class Student implements ComfyLife { … public void havePlentyFood() { System.out.println("lots of beer in the fridge"); } public void haveGoodTime() { System.out.println("partying all nights"); } }
Implements interface public class MScStudent extends Student implements ComfyLife { … public void havePlentyFood() { System.out.println("lots of healthy food in the fridge");}public void haveGoodTime() { System.out.println("really enjoyning the course");} }
Test the example public class TestStudentHierarchy { public static void main(String [] args) { Student s1=new Student("jane"); MScStudent ms1 = new MScStudent("mike"); s1.havePlentyFood(); s1.haveGoodTime(); ms1.haveGoodTime(); s1.haveGoodTime(); s1=ms1; s1.haveGoodTime(); } }
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.
Interfaces vs. Abstract Classes, cont. All data fields are publicfinalstatic and all methods are publicabstractin an interface. For this reason, these modifiers can be omitted, as shown below:
Whether to use an interface or a class? In general, a strong is-a relationship that clearly describes a parent-child relationship should be modeled using classes. For example, a staff member is a person. So their relationship should be modeled using class inheritance. A weak is-a relationship, also known as an is-kind-of relationship, indicates that an object possesses a certain property. A weak is-a relationship can be modeled using interfaces.
Interface to partially support multiple inheritance You can use interfaces to circumvent single inheritance restriction if multiple inheritance is desired. In the case of multiple inheritance, you have to design one as a superclass, and others as interface.
Enhance design using abstract classes and interfaces • By using abstract classes and interfaces, a programmer can identify the boundaries of different parts of a software system without having to provide details about their implementations. • Because abstract classes and interfaces do not specify how something is to be done, but rather something must be done, they are a good mechanism for determining parts early in the project. After defining a set of interfaces and abstract classes, various programmers can work in parallel.