Presentation is loading. Please wait.

Presentation is loading. Please wait.

UFCE3T-15-M Programming part 1 UFCE3T-15-M Object-oriented Design and Programming Block2: Inheritance, Polymorphism, Abstract Classes and Interfaces Jin.

Similar presentations


Presentation on theme: "UFCE3T-15-M Programming part 1 UFCE3T-15-M Object-oriented Design and Programming Block2: Inheritance, Polymorphism, Abstract Classes and Interfaces Jin."— Presentation transcript:

1 UFCE3T-15-M Programming part 1 UFCE3T-15-M Object-oriented Design and Programming Block2: Inheritance, Polymorphism, Abstract Classes and Interfaces Jin Sa

2 UFCE3T-15-M Programming part 2 Objectives F To understand the concept of inheritance. FTo develop a subclass from a superclass through inheritance.  To invoke the superclass ’ s constructors and methods using the super keyword. FTo override methods in the subclass. F To comprehend polymorphism. F To understand casting. FTo restrict access to data and methods using the protected visibility modifier. F To understand the concepts of abstract classes and interfaces FTo design and use abstract classes. F To declare interfaces to model weak inheritance relationships. F To know the similarities and differences between an abstract class and interface

3 UFCE3T-15-M Programming part 3 Inheritance and Polymorphism

4 UFCE3T-15-M Programming part 4 Superclasses and Subclasses

5 UFCE3T-15-M Programming part 5 Examples of Inheritance Student.java MScStudent.java TestStudentHierarchy.java

6 UFCE3T-15-M Programming part 6 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; } }

7 UFCE3T-15-M Programming part 7 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); } }

8 UFCE3T-15-M Programming part 8 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()); } }

9 UFCE3T-15-M Programming part 9 Using the Keyword super To call a superclass constructor To call a superclass method See the MSc example. The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways:

10 UFCE3T-15-M Programming part 10 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

11 UFCE3T-15-M Programming part 11 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.

12 UFCE3T-15-M Programming part 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 UFCE3T-15-M Programming part 13 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.

14 UFCE3T-15-M Programming part 14 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. 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. Circle c = new Circle(2.0); System.out.println(c.toString());

15 UFCE3T-15-M Programming part 15 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());

16 UFCE3T-15-M Programming part 16 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.

17 UFCE3T-15-M Programming part 17 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.

18 UFCE3T-15-M Programming part 18 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.

19 UFCE3T-15-M Programming part 19 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”);

20 UFCE3T-15-M Programming part 20 Example 8.1 Demonstrating Polymorphism and Casting See the TestStudentHierarchy example.

21 UFCE3T-15-M Programming part 21 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

22 UFCE3T-15-M Programming part 22 Accessibility Summary

23 UFCE3T-15-M Programming part 23 Visibility Modifiers

24 UFCE3T-15-M Programming part 24 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 be overridden by its subclasses.

25 UFCE3T-15-M Programming part 25 The equals Method The equals() method compares the contents 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); } For example, the equals method is overridden in the Circle class. public boolean equals(Object o) { if (o instanceof Circle) { return radius == ((Circle)o).radius; } else return false; }

26 UFCE3T-15-M Programming part 26 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.

27 UFCE3T-15-M Programming part 27 Abstract Classes and Interfaces

28 UFCE3T-15-M Programming part 28 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.

29 UFCE3T-15-M Programming part 29 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.

30 UFCE3T-15-M Programming part 30 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();

31 UFCE3T-15-M Programming part 31 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.

32 UFCE3T-15-M Programming part 32 The abstract Modifier The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses The abstract method –Method signature without implementation

33 UFCE3T-15-M Programming part 33 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.

34 UFCE3T-15-M Programming part 34 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.

35 UFCE3T-15-M Programming part 35 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

36 UFCE3T-15-M Programming part 36 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

37 UFCE3T-15-M Programming part 37 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; }

38 UFCE3T-15-M Programming part 38 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 }

39 UFCE3T-15-M Programming part 39 Interface example public interface ComfyLife { void havePlentyFood(); void haveGoodTime(); }

40 UFCE3T-15-M Programming part 40 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"); } }

41 UFCE3T-15-M Programming part 41 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"); } }

42 UFCE3T-15-M Programming part 42 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(); } }

43 UFCE3T-15-M Programming part 43 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.

44 UFCE3T-15-M Programming part 44 Interfaces vs. Abstract Classes, cont. All data fields are public final static and all methods are public abstract in an interface. For this reason, these modifiers can be omitted, as shown below:

45 UFCE3T-15-M Programming part 45 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.

46 UFCE3T-15-M Programming part 46 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.

47 UFCE3T-15-M Programming part 47 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.


Download ppt "UFCE3T-15-M Programming part 1 UFCE3T-15-M Object-oriented Design and Programming Block2: Inheritance, Polymorphism, Abstract Classes and Interfaces Jin."

Similar presentations


Ads by Google