Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Orientated Analysis, Design and Programming

Similar presentations


Presentation on theme: "Object-Orientated Analysis, Design and Programming"— Presentation transcript:

1 Object-Orientated Analysis, Design and Programming
Presentation by Dr. Phil Legg Senior Lecturer Computer Science 6: Inheritance, Abstract Class and Interface Autumn 2016

2 Objectives To learn what inheritance and polymorphism are, why we use them, and how to implement these within Java. To learn what abstract classes and interfaces are, why we use them, and how to implement these within Java.

3 Inheritance Inheritance is the mechanism by which attributes and behaviours are passed by a ‘superclass’ to a ‘subclass’ The subclass does not need to re-implement existing behaviour, it can use the existing behaviour and data by inheriting it.

4 Inheritance – Why? Person Student MSc Student Research Student
Customer Corporate Customer Individual Customer We may have many types of ‘person’ – we may need some specialist fields (e.g., degree), yet there may be generic fields also (e.g., gender).

5 What to Inherit Subclass inherits from a Superclass all superclass behaviours and attributes The subclass even receive all the relationships of its superclass. The subclass may provide additional attributes and behaviours, relevant to its specialised level of abstraction. Subclass may modify the behaviours it inherits from its superclass.

6 When to Inherit Avoid duplication in functionality.
There is some common functionality. Don’t confuse object instances with inheritance. Inheritance implies different types, not different instances of the same type.

7 Implementing Inheritance in Java
Java allows you to derive new classes from existing classes using “extends” Example: student class and MSc student class. Student class: Attributes: name, mark Methods: getMark , setMark. MScStudent class could be derived from the Student class, therefore inheriting the variables and methods contained in the Student class. New attribute: supervisor and method: chooseSupervisor

8 Inheritance – Example public class Student { private String name;
private int mark; public void setName(String n){ name=n;} public String getName() { return name;} public void setMark(int m) { mark=m;} public int getMark(){ return mark;} } public class MScStudent extends Student { private String supervisor; public void chooseSupervisor(String nm) { supervisor=nm;} public String getSupervisor() { return supervisor;} } public class TestInheritance { public static void main(String [] args) { MScStudent s2=new MScStudent(); s2.setName("Mike"); s2.chooseSupervisor("Jane"); System.out.println("s2 is "+ s2.getName()+ "--Supervisor is "+s2.getSupervisor()); }

9 Activity Implement Student and MScStudent
Explore private and public attributes Add a new method in the MScStudent class. The new method should access the value of the variable name. e.g. public String getName(){return name;} Can you compile MScStudent now?

10 Both classes have toString method however they are different
Overriding Methods public class Student { private String name; int mark; … other methods public String toString() { return "Name: "+name+ "Mark: "+mark; }  public class MScStudent extends Student { private String supervisor; MScStudent(String nm){ super(nm);} … other methods public String toString(){ String ss=super.toString(); return ss+“ supervisor: "+supervisor; } public class TestPoly { public static void main(String [] args) { Student s1=new Student("Kate"); System.out.println(s1.toString()); s1=new MScStudent("Mike"); } Both classes have toString method however they are different

11 Polymorphic The term polymorphism: “having many forms”.
A polymorphic reference is a reference variable that can refer to different types of objects at different points in time 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 provides a means to an elegant versatility in our software. It allows us to provide a consistent approach to different but related behaviours.

12 Polymorphic - Example public class TestPoly2 { public static void main(String [] args) { Student [] all= new Student[3]; all[0]= new Student("kate"); all[1]= new MScStudent("mike"); all[2]= new Student("Jane"); for (int i=0;i<3;i++) System.out.println(all[i].toString()); } Array of Students – yet we can have MScStudents stored also. Must have toString in the superclass

13 Casting Casting can be used to convert an object of one class type to another within an inheritance hierarchy. There are implicit casting and explicit casting. Student s = new MScStudent(“Mike”); assigns an MScStudent object to a reference of the Student type. This statement involves an implicit casting. This is legal because an instance of MScStudent is an instance of Student.

14 Explicit Casting Explicit casting must be used when casting an object from a superclass to a subclass. Student s=new MScStudent("Mike"); s.chooseSupervisor(“Helen”); s is a reference of type Student. Since the Student class does not have the method chooseSupervisor, the compiler doesn’t know that the object pointed by s has the chooseSupervisor method. So, we have to explicitly cast s to MScStudent as follows:   ((MScStudent)s).chooseSupervisor(“Helen”);

15 Break 5 minute break

16 Abstract Class Concrete classes can have (direct) instances.
However, an Abstract class cannot have its own (direct) instances. Abstract classes exist purely to generalize common behaviour that would otherwise be duplicated across (sub)classes. Abstract classes (normally) have abstract methods.

17 Abstract Class - Example
The Employee class contains one abstract method called calculatePay(). It is an abstract method with no implementation. Each of the subclasses provides its own implementation of the calculatePay method. This means that each class provides an implementation of the abstract behaviour but each subclass does that in a slightly different way.

18 Abstract Class - Example
Class must be declared as abstract. Typically an abstract class contains one or more abstract method. Use abstract classes when you need to provide some functionality but also wish to defer some implementation to the subclasses. In UML it is shown in italics.

19 Inheritance Mechanisms
Inheritance of Implementation. The operation signature and implementation method are passed without modification from superclass to subclass. Inheritance of Interface. The superclass offers an abstract operation signature. The subclass inherits the operation signature but must provide an implementation method if the class is to be concrete, i.e. have instances. Overriding Inheritance. The operation signature and method are inherited by the subclass but the method is modified to exhibit behaviour appropriate to that class.

20 Abstract Class in Java Consider an application that deals with different shapes Circle, Triangle, Square Common attributes and methods: colour, findArea() How to define findArea() for the Shape class? Java provides ‘abstract method’ to allow for such methods. Abstract methods do not have any definition. public abstract class Shape { private String colour="red"; … …//other methods public String toString(){ return "Colour is:"+ colour; } public abstract double findArea(); public class Square extends Shape{ private double length; public Square(double l) { length=l; } public double findArea(){ return length*length;

21 Abstract Class in Java Abstract methods such as findArea() provide “place holders” for methods that can sensibly be mentioned at one level, but that are going to be implemented in a variety of ways in the subclasses. An abstract class is a class usually with at least one abstract method. Abstract classes cannot have instances. public abstract class Shape { private String colour="red"; … …//other methods public String toString(){ return "Colour is:"+ colour; } public abstract double findArea(); public class Square extends Shape{ private double length; public Square(double l) { length=l; } public double findArea(){ return length*length;

22 Interface An interface is an elegant way of defining the public services that a class will provide without being bogged down by implementation details. Think of an interface as a business contract between two parties. The class implementing the interface agrees to provide the services defined in that interface to other classes. Interface has no attribute

23 Interface in Java An interface is a class like construct that contains only constants and abstract methods. An interface defines the specification of a set of constants and methods. The interface acts as a guarantee or a contract: any class that implements the interface is guaranteed to provide implementations for these abstract methods. 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.

24 Interface - Example public interface LifeStyle{ void haveGoodFood();
void haveAccommodation(); } public class MScStudent2 extends Student implements LifeStyle{ private String supervisor; MScStudent2(String nm){ super(nm);} … … //other methods public void haveGoodFood(){ System.out.println("Lots of bread, meat and veg"); } public void haveAccommodation(){ System.out.println("have a single room in a shared house");

25 Interface in Java An interface defines a set of constants and abstract methods. Very similar to an abstract class that contains only abstract methods. (Normally) No attribute. Sometimes an interface will contain attributes as well, but in those cases, the attributes are usually static and are often constants. public interface System { public void send(Message message); } In UML, an interface can be shown as a stereotyped class notation or by using its own ball notation

26 Interface - Example public interface EmailSystem {
public void send(Message message)); } public class SMTPMailSystem implements System { public void send(Message message) { // Implement the interactions // with an SMTP server to // send the message }

27 Interface as a Contract
The interface acts as a guarantee or a contract: any class that implements the interface is guaranteed to provide implementations for these abstract methods Think of an interface as a very simple contract that declares, “These are the operations that must be implemented by classes that intend to meet this contract.”

28 Interfaces and multiple Inheritance
Interfaces tend to be much safer to use than abstract classes because they avoid many of the problems associated with multiple inheritance This is why programming languages such as Java allow a class to implement any number of interfaces, but a class can inherit from only one regular or abstract class. Example teaching assistant: is a student and is a staff

29 Abstract Classes vs Interfaces
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.

30 Abstract Classes vs Interfaces
A strong is-a relationship that clearly describes a parent-child relationship should be modeled using classes. 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. Interfaces can partially support multiple inheritances.

31 In-Class Activity Let’s model the concept of a pet. A pet has a name;
it has activities. For example, a fish swims; a cat catches mice and a dog guards home. Define a collection of classes that would model the concepts of pet, fish, cat and dog. Provide suitable methods to display the information about a pet, including its name and the kind of activity it can do. Define a testing class in which you create some instances of Fish, Cat and Dog and display the information of these pets.

32 In-Class Activity Modify the above program. Create a collection of pets. Provide a polymorphic solution to display the information of each pet.


Download ppt "Object-Orientated Analysis, Design and Programming"

Similar presentations


Ads by Google