Chapter 03: Inheritance and Polymorphism PDF

Document Details

FineEnlightenment390

Uploaded by FineEnlightenment390

Wachemo University College of Natural and Computational Science

Tags

java programming inheritance polymorphism object-oriented programming

Summary

This document is a Java programming lecture or study guide focusing on inheritance and polymorphism concepts. It's intended for undergraduate-level computer science students learning about object-oriented programming techniques in Java. The document provides an overview of the topic and features examples and diagrams to illustrate the concepts.

Full Transcript

CHAPTER 03 Inheritance and Polymorphism 1 Objectives After studying this chapter, students should be able to learn: Basics of Inheritance Types of Inheritance The protected modifier Polymorphism and its types The Object c...

CHAPTER 03 Inheritance and Polymorphism 1 Objectives After studying this chapter, students should be able to learn: Basics of Inheritance Types of Inheritance The protected modifier Polymorphism and its types The Object class The Abstract class 2 Introduction Object-oriented programming (OOP) is popular because: – It enables reuse of previous code saved as classes All Java classes are arranged in a hierarchy – Object is the superclass of all Java classes Inheritance and hierarchical organization capture idea: – One thing is a refinement or extension of another Reusability - building new classes by utilizing existing classes. 3 Inheritance - Introduction  It is always good/“productive” if we are able to reuse something that already exists rather than creating the same all over again.  This is achieved by creating new classes, reusing the data members and methods of existing classes.  This mechanism of deriving a new class from existing/old class is called “inheritance”.  The old class is known as “base” class, “super” class or “parent” class”; and the new class is known as “sub” class, “derived” class, or “child” class. 4 Examples subclass superclass Parent Inherited or extends or capability derived class base class Child 5 Examples – Contd. Figure : Class Hierarchies 6 Contd. Inheritance relationships often are shown graphically in a UML class diagram, with an arrow with an open arrowhead pointing to the parent class. Vehicle Car Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent. 7 Declaring Sub classes In Java, we use the reserved word extends to establish an inheritance relationship class subclass-name extends superclass-name { ………… ………… } class Car extends Vehicle { // class contents } 8 Types of Inheritance The different types of inheritance are: – Single inheritance (only one super class) – Multiple inheritance (several super classes, not supported by Java) – Hierarchical inheritance (one super class, many sub classes) – Multi-Level inheritance (derived from a derived class) – Hybrid inheritance (more than two types) – Multi-path inheritance (inheritance of some properties from two sources). 9 Types of Inheritance A A B A B C B C D (a) Single Inheritance (b) Multiple Inheritance (c) Hierarchical Inheritance A A A B C B C B C D D (d) Multi-Level Inheritance (e) Hybrid Inheritance (f) Multipath Inheritance 10 The protected Modifier Visibility modifiers determine which class members are inherited and which are not Variables and methods declared with public visibility are inherited; those with private visibility are not But public variables violate the principle of encapsulation There is a third visibility modifier that helps in inheritance situations: protected 11 The protected Modifier The protected visibility modifier allows a member of a base class to be accessed in the child – protected visibility provides more encapsulation than public does – protected visibility is not as tightly encapsulated as private visibility Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N none Y Y N N private Y N N N 12 Single Inheritance - Example public class Person { Person class contains general details of a String name; person String permanentAddress; int age; void set_PermanentDetails(String name, String permanentAddress, int age) { this.name = name; this.permanentAddress = permanentAddress; this.age = age; } void get_PermanentDetails() { System.out.println("Name : " + name); System.out.println("Permanent Address : " + permanentAddress); System.out.println("Age :" + age); } } 13 class Employee extends Person { Contd. int id; Employee contains company details of a person. Reuse the general details of the String companyName; person in its sub class. String companyAddress; Employee(int id, String name, String permanentAddress, int age, String companyName, String companyAddress) { this.id = id; set_PermanentDetails(name, permanentAddress, age); this.companyName = companyName; this.companyAddress = companyAddress; } void get_EmployDetails() { System.out.println("Employ Id : " + id); get_PermanentDetails(); System.out.println("Company Name : " + companyName); System.out.println("Company Address : " + companyAddress); } } 14 class InherDemo { Contd. public static void main(String args[]) { Employee e1 = new Employee(301, “Ahmed", "Addis Ababa, Ethiopia",29, “WCU", “Hossana, Ethiopia"); e1.get_EmployDetails(); } } Output: Employ Id : 301 Name : Ahmed Permanent Address : Addis Ababa, Ethiopia Age :29 Company Name : WCU Company Address : Hossana, Ethiopia 15 Multilevel Inheritance - Example public class Student { int id; Scanner in = new Scanner(System.in); void readdata1() { System.out.print("Enter your Id: "); id = in.nextInt(); } void printdata1() { System.out.println("Id = " + id); } } 16 Contd. class Exam extends Student { int m1, m2, m3; Scanner in = new Scanner(System.in); void readdata2() { readdata1(); System.out.print("Enter 3 subjects marks:"); m1 = in.nextInt(); m2 = in.nextInt(); m3 = in.nextInt(); } void printdata2() { printdata1(); System.out.println("Subject1 marks=" + m1); System.out.println("Subject2 marks=" + m2); System.out.println("Subject3 marks=" + m3); } } 17 Contd. class Results extends Exam { int avg; void printdata3() { printdata2(); avg = (m1 + m2 + m3) / 3; if (avg < 35) { System.out.println("Grade: Fail"); } else if (avg >= 35 && avg < 50) { System.out.println("Grade: D"); } else if (avg >= 50 && avg < 60) { System.out.println("Grade: C"); } else if (avg >= 60 && avg < 75) { System.out.println("Grade: B"); } else if (avg >= 75) { System.out.println("Grade: A"); } } } 18 Contd. class MultiInh { public static void main(String sad[]) { Results obj = new Results(); obj.readdata2(); obj.printdata3(); } } Output: Enter your Id: 101 Enter 3 subjects marks:75 82 95 Id = 101 Subject1 marks=75 Subject2 marks=82 Subject3 marks=95 Grade: A 19 Using “super” keyword ‘super’ is a keyword used to refer to hidden variables of super class from sub class. super.a=a; It is used to call a constructor of super class from constructor of sub class which should be first statement. super(a,b); It is used to call a super class method from sub class method to avoid redundancy of code super.addNumbers(a, b); 20 “super” and hiding Why is super needed to access super-class members? When a sub-class declares the variables or methods with the same names and types as its super-class: class A { int i = 1; } class B extends A { int i = 2; System.out.println(“i is “ + i); } The re-declared variables/methods hide those of the super-class. 21 class A { “super” - Example int i; } class B extends A { int i; B(int a, int b) { super.i = a; i = b; } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } 22 Contd. Although the i variable in B hides the i variable in A, super allows access to the hidden variable of the super-class: class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } 23 Multiple Inheritance Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents Collisions, such as the same variable name in two parents, have to be resolved Java does not support multiple inheritance In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead. 24 Using final keyword with Inheritance final keyword is used declare constants which can not change its value of definition. final variables can not change its value. final methods can not be Overridden or Overloaded final Classes can not be extended or inherited 25 Preventing Overriding with final A method declared final cannot be overridden in any sub-class: class A { final void meth() { System.out.println("This is a final method."); } } This class declaration is illegal: class B extends A { void meth() { System.out.println("Illegal!"); } } 26 Contd. A class declared final cannot be inherited – has no sub-classes. final class A { … } This class declaration is considered illegal: class B extends A { … } Declaring a class final implicitly declares all its methods final. It is illegal to declare a class as both abstract and final. 27 The Benefits of Inheritance Code reusability:- Inheritance automates the process of reusing the code of the super classes in the subclasses. – With inheritance, an object can inherit its more general properties from its parent object, and that saves the redundancy in programming. Code maintenance:- Organizing code into hierarchical classes makes its maintenance and management easier. Implementing OOP:- Inheritance helps to implement the basic OOP philosophy to adapt computing to the problem and not the other way around, because entities (objects) in the real world are often organized into a hierarchy. Increased Reliability (resulting from reuse and sharing of well-tested code) Information Hiding 28 Polymorphism Polymorphism came from the two Greek words ‘poly’ means many and morph means forms i.e. many forms If the same method has ability to take more than one form to perform several tasks then it is called polymorphism. A polymorphic reference is a variable that can refer to different types of objects at different points in time. It is of two types: Static Polymorphism and Dynamic Polymorphism. Static Polymorphism: – The polymorphism exhibited at compile time is called Static polymorphism. – Here the compiler knows which method is called at the compilation. This is also called compile time polymorphism or static binding. – Achieving method overloading & method overriding using private, static and final methods is an example of Static Polymorphism. 29 Static Polymorphism class Animal { static void move () { System.out.println ("Animals can move"); } } class Dog extends Animal { static void move () { System.out.println ("Dogs can walk and run"); } } public class StaticPoly { public static void main(String args[]) { Animal.move (); Dog.move (); } } 30 Polymorphism – Contd. Dynamic Polymorphism: – The polymorphism exhibited at run time is called dynamic polymorphism. – In this dynamic polymorphism a method call is linked with method body at the time of execution by JVM. – Java compiler does not know which method is called at the time of compilation. This is also known as dynamic binding or run time polymorphism. – Method overloading and method overriding are examples of Dynamic Polymorphism in Java. 31 Dynamic Polymorphism - overloading class Sample { void add(int a,int b) { System.out.println ("sum of two="+ (a+b)); } void add(int a,int b,int c) { System.out.println ("sum of three="+ (a+b+c)); } } class OverLoad { public static void main(String[] args) { Sample s=new Sample ( ); s.add (20, 25); s.add (20, 25, 30); } } 32 Method Overriding Writing two or more methods in super & sub classes with same name and same signatures is called method overriding. In method overriding JVM executes a method depending on the type of the object. class Animal { void move() { System.out.println ("Animals can move"); } } class Dog extends Animal { void move() { System.out.println ("Dogs can walk and run"); } 33 } public class OverRide Contd. { public static void main(String args[]) { Animal a = new Animal (); // Animal reference and object Animal b = new Dog (); // Animal reference but Dog object a.move (); // runs the method in Animal class b.move (); //Runs the method in Dog class } } 34 Overloading Vs Overriding Overloading deals Overriding deals with with multiple two methods, one in a methods in the parent class and one same class with the in a child class, that same name but have the same different signatures signature Overloading lets you Overriding lets you define a similar define a similar operation in operation in different different ways for ways for different different data object types 35 The Object class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies. The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we define the toString method, we are actually overriding an inherited definition 36 Contd. The toString method in the Object class is defined to return a string that contains the name of the object’s class along with some other information The equals method of the Object class returns true if two references are aliases We can override equals in any class to define equality in some more appropriate way As we've seen, the String class defines the equals method to return true if two String objects contain the same characters The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version 37 The Abstract Class A method with method body is called concrete method. In general any class will have all concrete methods. A method without method body is called abstract method. A class that contains abstract method is called abstract class. i.e. An abstract class is a class with zero or more abstract methods It is possible to implement the abstract methods differently in the subclasses of an abstract class. These different implementations will help the programmer to perform different tasks depending on the need of the sub classes. Moreover, the common members of the abstract class are also shared by the sub classes. 38 Contd. The abstract methods and abstract class should be declared using the keyword abstract. We cannot create objects to abstract class because it is having incomplete code. Whenever an abstract class is created, subclass should be created to it and the abstract methods should be implemented in the subclasses, then we can create objects to the subclasses. Abstract class reference can be used to refer to the objects of its sub classes. Abstract class references cannot refer to the individual methods of sub classes. A class cannot be both ‘abstract’ & ‘final’. e.g.: final abstract class A // invalid 39 Example – Abstract class abstract class Figure { double dim1; double dim2; Figure (double a, double b) { dim1 = a; dim2 = b; } abstract double area ();// area is an abstract method } class Rectangle extends Figure { Rectangle (double a, double b) { super (a, b); } double area () // override area for rectangle { System.out.println ("Inside Area of Rectangle."); return dim1 * dim2; } } 40 Contd. class Triangle extends Figure { Triangle (double a, double b) { super (a, b); } double area() // override area for right triangle { System.out.println ("Inside Area of Triangle."); return dim1 * dim2 / 2; } } class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); System.out.println("Area is " + r.area()); System.out.println("Area is " + t.area()); } } 41 THANK YOU 42

Use Quizgecko on...
Browser
Browser