[go: up one dir, main page]

0% found this document useful (0 votes)
21 views12 pages

Chapter- 3 Inheritance and Polymorphism-1x4

The document provides an overview of inheritance and polymorphism in object-oriented programming, detailing concepts such as super-classes, sub-classes, method overriding, and overloading. It explains how inheritance allows new classes to derive properties and behaviors from existing classes, promoting code reusability. Additionally, it outlines rules and types of inheritance in Java, including single and multi-level inheritance.

Uploaded by

joshua211619
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views12 pages

Chapter- 3 Inheritance and Polymorphism-1x4

The document provides an overview of inheritance and polymorphism in object-oriented programming, detailing concepts such as super-classes, sub-classes, method overriding, and overloading. It explains how inheritance allows new classes to derive properties and behaviors from existing classes, promoting code reusability. Additionally, it outlines rules and types of inheritance in Java, including single and multi-level inheritance.

Uploaded by

joshua211619
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

5/29/2023

Chapter Outlines
 Introduction Inheritance
 Super-classes and Sub-classes
 Using the super Keyword
 Method Overriding and Overloading
 Polymorphism
 Casting Objects and Instance Operator
Inheritance and Polymorphism
 The Object Class
 Abstract Classes
 Interfaces
 Using Interfaces

Object Oriented Programming - CoSc2051 1 Object Oriented Programming - CoSc2051 2

Introduction to Inheritance Introduction to Inheritance


 In the real world:  Object-oriented programming allows you to define new classes
 We inherit traits from our mother and father. from existing classes.
 We also inherit traits from our grandmother, grandfather, and  This is called inheritance.

ancestors.  The procedural paradigm focuses on designing methods and the

 We might have similar eyes, the same smile, a different height . . .


object-oriented paradigm couples data and methods together into
objects.
but we are in many ways "derived" from our parents.
 Inheritance is an important and powerful feature for reusing
 In software:
software.
 Object inheritance is well defined!
 what is the best way to design classes so as to avoid redundancy
 Objects that are derived from other object "resemble" their
and make then system easy to comprehend and easy to maintain?
parents by inheriting both state (fields) and behavior (methods).
 The answer is to use inheritance.

Object Oriented Programming - CoSc2051 3 Object Oriented Programming - CoSc2051 4


5/29/2023

Introduction to Inheritance Introduction to Inheritance


 Super-classes and Sub-classes  Super-classes and Sub-classes
 Different classes may have some common properties and  A superclass is also referred to as a parent class or a base class, and a
behaviors:- subclass as a child class, an extended class, or a derived class.
 which can be generalized in a class that can be shared by other  A subclass inherits accessible data fields and methods from its
classes. superclass and may also add new data fields and methods.
 You can define a specialized class that extends the generalized class.  The keyword “extends” used to create inheritance in java.
 The specialized classes inherit the properties and methods from the
general class.
 In Java terminology, a class C1 extended from another class C2 is called
a subclass, and C2 is called a superclass.

Object Oriented Programming - CoSc2051 5 Object Oriented Programming - CoSc2051 6

Introduction to Inheritance Introduction to Inheritance


.

Dog Cat  Super-classes and Sub-classes


String name String name
int fleas int hairballs
 Note the following points regarding inheritance:
String getName() String getName()  Contrary to the conventional interpretation, a subclass is not a subset of
int getFleas() int getHairballs()
void spark() void spark() its superclass.
using  In fact, a subclass usually contains more information and methods
inheritance

superclass than its superclass.


Animal
String name  Private data fields in a superclass are not accessible outside the class.
String getName() subclass  Therefore, they cannot be used directly in a subclass.
subclass void spark()
 They can, however, be accessed/mutated through public accessors or
/mutators if defined in the superclass.
Dog Cat
int fleas int hairballs  Not all is-a relationships should be modeled using inheritance.
int getFleas() int getHairballs()

Object Oriented Programming - CoSc2051 7 Object Oriented Programming - CoSc2051 8


5/29/2023

Recap Introduction to Inheritance


1. True or false? A subclass is a subset of a superclass.  Using the super Keyword
2. What keyword do you use to define a subclass?  The keyword super refers to the superclass and can be used to invoke

3. What is single class? the superclass’s methods and constructors.


 A subclass inherits accessible data fields and methods from its superclass.
 The keyword super refers to the superclass of the class in which super
appears.
 It can be used in two ways:
 To call a superclass constructor.
 To call a superclass method.
 To call superclass method we use super.method(parameters);

Object Oriented Programming - CoSc2051 9 Object Oriented Programming - CoSc2051 10

Introduction to Inheritance Introduction to Inheritance


 Using the super Keyword public class Rectangle {

 Calling Superclass Constructors:  Calling


double Superclass Constructors:
width;
double length;
 A constructor is used to construct an instance of a class.  A constructor is used to construct an instance of a class.
 Unlike properties and methods, the constructors of a superclass are not // constructor used when no dimensions specified
 Unlike {properties and methods, the constructors of a superclass are
Rectangle()
inherited by a subclass. width = ‐1; // use ‐1 to indicate an uninitialized
not inherited by a subclass.
length = ‐1;
 They can only be invoked from the constructors of the subclasses using
 They
} can only be invoked from the constructors of the subclasses
the keyword super. // constructor used when all dimensions specified
using the
Box(double keywordl)super.
w, double {
 The syntax to call a superclass’s constructor is: width = w; length = l;
}  The syntax to call a superclass’s constructor is:
super(), or super(parameters); // compute and return volume
super(), or super(parameters);
double area() {
public ClassName() { return width * length;
public ClassName() {
super(); }
// some statements Equivalent
// some statements }
}
}
Object Oriented Programming - CoSc2051 11 Object Oriented Programming - CoSc2051 12
5/29/2023

Introduction to Inheritance Introduction to Inheritance


public class Box { public
public class
class Box {
TestDemoSuper {
// BoxWeight now uses super to initialize its Box attributes.
public class Cuboid extends Rectangle{
 Calling
double Superclass Constructors:
width; Calling
public
double Superclass
width;
static Constructors:
void main(String[] args) {
double height; double height;
double height; // weight of box
 Adepth;
double constructor is used to construct an instance of a class. double Adepth;
Cuboid constructor
cb is used to20,
= new Cuboid(10, construct
15); an instance of a class.
Cuboid cb2= new Cuboid(); // default
 Unlikeconstructor
// default
// constructorproperties and no
used when methods,
dimensions the constructors
specified of a superclass are  Unlike properties
// constructor and no
used when methods,
dimensionsthe constructors
specified of a superclass are
Cuboid() {
Box() { Box()
double{
not inherited by a subclass.
super(); not inherited by a subclass.
vol;
width = ‐1; // use ‐1 to indicate width = ‐1; // use ‐1 to indicate
vol= cb.volume();
height = ‐1;
} They can only be invoked from the constructors of the subclasses  They can =only
height = ‐1; // an uninitialized height ‐1;be//
invoked from the constructors of the subclasses
an uninitialized
depth = ‐1; // box depth = ‐1; // box of mybox1 is " + vol);
System.out.println("Volume
} using the keyword super. using the keyword super.
}System.out.println();
// initialize width, height, and depth using super()
// constructor used when all dimensions specified // constructor used when all dimensions specified
 The syntax
Cuboid(double
Box(double to call
w, double
w, double a superclass’s
l,
h, double
double h) {constructor is:
d) {  The syntax
Box(double w, doubleto call a superclass’s
h, double d) { constructor is:
super(w, l); // call superclass constructor vol = cb2.volume();
width = w; height = h; depth = d; width = w; height = of
System.out.println("Volume h; cb2depth is =" d;
+ vol);
}
super(),
height = h; or super(parameters); super(), or super(parameters);
}System.out.println();
}
// compute and return volume // compute} and return volume
}
double volume() { double
} volume() {
return width * height * depth; return width * height * depth;
} }
} Object Oriented Programming - CoSc2051 13 } Object Oriented Programming - CoSc2051 14

Introduction to Inheritance Introduction to Inheritance


 Types of Inheritance in Java  Single level Inheritance in Java
 In single inheritance, one class inherits the properties of another.
 It enables a derived class to inherit the properties and behavior from a
single parent class.
 This will, in turn, enable code reusability as well as add new features to
the existing code.

Cat Extends Animal

Object Oriented Programming - CoSc2051 15 Object Oriented Programming - CoSc2051 16


5/29/2023

Introduction to Inheritance Introduction to Inheritance


 Single level Inheritance in Java  Multi-level Inheritance in Java
 When a class is derived from a class which is also derived from another
class Animal {
public void eat(){System.out.println(“eating”); class, i.e. a class having more than one parent class but at different levels,
 In single} inheritance, one class inherits the properties of
} such type of inheritance is called Multilevel Inheritance.
another.
class Dog extends Animal {
void bark(){ Extends
 It enables a derived class to inherit the properties and
System.out.println(“barking”);
Extends
} Puppy Dog Animal
behavior
} from a single parent class.
class TestInheritance {
 This
publicwill, in turn,
static enable
void code reusability
main(String args[]) { as well as add new
Dog d = new Dog();
featuresd.bark();
to the existing code.
d.eat();
}
} Extends

Object Oriented Programming - CoSc2051 17 Object Oriented Programming - CoSc2051 18

Introduction to Inheritance Introduction to Inheritance


 Multi-level Inheritance in Java  Recap
class Animal {
void eat(){  RULE 1: Multiple Inheritance is NOT permitted in Java.
System.out.println(“eating…”);}  RULE 2: Cyclic Inheritance is NOT permitted in Java.
}
class Dog extends Animal {  RULE 3: Private members do NOT get inherited.
void bark(){
System.out.println(“barking…”);}  RULE 4: Constructors cannot be Inherited in Java.
}  RULE 5: In Java, we assign parent reference to child objects.
class Puppy extends Dog {
void weep(){  RULE 6: Constructors get executed because of super() present in the
System.out.println(“weeping…”);}
} constructor.
Extends Extends
class TestInheritance2 {
Dog Animal
public static void main(String args[]) {
Puppy d = new Puppy();
d.weep();
d.bark();
d.eat();
} }
Object Oriented Programming - CoSc2051 19 Object Oriented Programming - CoSc2051 20
5/29/2023

Method Overriding and Overloading Method Overriding and Overloading


 Method Overriding  Method Overriding
 Re defining the method of the Super Class in the Sub Class. class super {
public void display() {
 Inheritance in java involves a relationship between parent and child
System.out.println(“Hello”);
classes. }
}
 Whenever both the classes contain methods with the same name and class sub extends super {
arguments or parameters it is certain that one of the methods will
public void display() {
override the other method during execution. System.out.println(“Hello Welcome”);
}
 Method will be called depending on the object. }
 Method overriding is achieved in Inheritance.

The same method display() in super and sub class

Object Oriented Programming - CoSc2051 21 Object Oriented Programming - CoSc2051 22

Method Overriding and Overloading Method Overriding and Overloading


 Method Overriding  Method Overriding
 When the sub class object is called then the display() method  Do’s and Don’ts of Overriding.
inherited from the super class is shadowed and the sub class  Signature must be same in method overriding.
display() method is executed.  If the method parameter is different the method is not overridden
 Super Class method never be called upon the object of Sub Class. but it is overloaded.
 In the given example program the super class have a method called  Return type must be same, if it is not same then the method is
display() which is saying hello and another class sub class is taken where neither overridden nor overloaded.
it inherits the display() method from super class and re defines the  Final and static methods cannot be overridden.
method.  Method can be overridden with same (public, protected,private) access
specifiers but the stricter(private) access specifiers cannot be used in sub
class.

Object Oriented Programming - CoSc2051 23 Object Oriented Programming - CoSc2051 24


5/29/2023

Method Overriding and Overloading Method Overriding and Overloading


 Method Overloading  Method Overloading
 Overloading methods enables you to define the methods with the same name //method overloading

It is compile-time polymorphism.
as long as their signatures are different. public int max(double num1, double num2) {
if (num1 > num2) {
 Although we can overload static methods, the arguments or input return num1;
} else {
parameters have to be different. return num2;
 We cannot overload two methods if they only differ by a static keyword. }
}
 Like other static methods, the main() method can also be overloaded. public int max(int num1, int num2,int num3) {
if (num1 > num2 && num1>num3) {
return num1;
} else if (num2>num3){
Method(X) return num2;
}
Same class else {return num3;}
Method(X,Y)
}
• You can have this three method in
Method(X,Y, Z)
single class
Object Oriented Programming - CoSc2051 25 Object Oriented Programming - CoSc2051 26

Method Overriding and Overloading Method Overriding and Overloading


 Method Overloading  Method Overloading Tips

 Overloading methods can make programs clearer and more readable.


 Consider the following code:
public class AmbiguousOverloading {
 Methods that perform the same function with different types of
public static void main(String[] args) {
parameters should be given the same name.
ambiguous
 Overloaded methods must have different parameter lists. System.out.println(max(1, 2));
} invocation
 You cannot overload methods based on different modifiers or return public static double max(int num1, double num2) {
if (num1 > num2)
types. return num1;
else
 Sometimes there are two or more possible matches for the invocation of return num2;
}
a method, but the compiler cannot determine the best match. This is public static double max(double num1, int num2) {
if (num1 > num2)
referred to as ambiguous invocation. return num1;
else
 Ambiguous invocation causes a compile error. return num2;
}
}
Object Oriented Programming - CoSc2051 27 Object Oriented Programming - CoSc2051 28
5/29/2023

Method Overriding and Overloading Polymorphism


Difference between Method Overloading and Method Overriding  Assuming different forms. “Poly” means numerous, and “Morphs”

Method Overloading Method Overriding means forms.


 Polymorphism means that a variable of a supertype can refer to a
 It is used to increase the readability of the  Provides a specific implementation of the
program method already in the parent class subtype object.
 Polymorphism in OOP is the ability of an object to take several forms.
 It is performed within the same class  It involves multiple classes
 Polymorphism literally means “being able to assume different forms.”
 Parameters must be different in case of  Parameters must be same in case of
overloading overriding  Polymorphism is an important and powerful concept in OOP.
 Is an example of compile-time
 It is an example of runtime polymorphism
 It is the ability to process objects in a hierarchy differently depending on
polymorphism
their actual class type.
 Return type must be same in overriding

 Overriding does not involve static


 Static methods can be overloaded
methods.
Object Oriented Programming - CoSc2051 29 Object Oriented Programming - CoSc2051 30

Polymorphism Polymorphism
 Polymorphism just means that different objects can respond to the
same message in different ways.
 Example:
 Polymorphism can work for both variables/states and
 The human body has different organs. Every organ has a different
methods/behaviors of objects.
function to perform;
 However, two powerful polymorphic concepts are often useful when you
class Shapes {
define a class: (Types of Polymorphism-) public void area() {
System.out.println("The formula for area of ");
 method overloading and method overriding. }
}
or Compile-time and Run-time class Triangle extends Shapes {
public void area() {
 Java implements polymorphism through method overloading and method System.out.println("Triangle is ½ * base * height ");
}
overriding. }
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
Object Oriented Programming - CoSc2051 31 } Object Oriented Programming - CoSc2051 32
5/29/2023

Typecasting in Java Typecasting in Java


 One object reference can be typecast into another object reference. This is  Student b = (Student)o; // Explicit casting
called casting object.  It is always possible to cast an instance of a subclass to a variable of a
 In the preceding section, the statement superclass (known as upcasting).
m(new Student());  Type casting for primitive data type to another.
 assigns the object new Student() to a parameter of the Object type. int age = 45;
 This statement is equivalent to:
// A new value is assigned to newAge
Object o = new Student(); // Implicit casting byte newAge = (byte)age;
m(o);  However, casting an object reference does not create a new object.
 The statement Object o = new Student(), known as implicit casting, is legal  For example
because an instance of Student is an instance of Object.
Object o = new Circle();
Circle c = (Circle)o; // No new object is created

Object Oriented Programming - CoSc2051 33 Object Oriented Programming - CoSc2051 34

Abstract Classes Abstract Classes


 There are two types of classes Abstract class and Concrete class.  Ways to achieve Abstraction in Java
 An abstract class is a class that cannot be instantiated—we cannot create  The process of Abstraction in Java can be achieved by the following two
instances of an abstract class. methods as mentioned below:
 One or more methods may be declared, but not defined.  Implementing an Abstract Class
(The programmer has not yet written code for a few methods).  Implementing an Interface
 The declared methods and classes have the keyword abstract in their  The Syntax for Abstract Classes Abstract class may
have also
signature. //a super abstract class non-abstract method
 If abstract keyword is used before the class then it is an Abstract Class if abtract class Super { which has a body
abstract void method();
nothing is written before class then it is a Concrete class. }

 Reference of abstract class is allowed.  Abstract class can include Abstract and Non-Abstract methods in them.
 They can include constructors and static methods.

Object Oriented Programming - CoSc2051 35 Object Oriented Programming - CoSc2051 36


5/29/2023

Abstract Classes Abstract Classes


//a super abstract class
class test {
abstract class Super {
 Object of an Abstract class cannot be created but object of public static void main() {
Super() {
Super s1; // reference of abstract is allowed
Concrete class can be created.
System.out.println(“Super”);
} abstract class and sub s2 =new sub();
abstract method
 Reference of abstract
void meth1() { class is allowed. }
System.out.println(“meth1”);
 Example:
} }
abstract void meeth2();
}  Object of an Abstract class cannot be created but object of Concrete class can be
created.
//concrete class
class sub extends Super {  Reference of abstract class is allowed.
 Example: Method which is not having a body is known as Abstract method, the
Void meth2() {
System.out.println(“meth2”); method must be declared as abstract.
}  The abstract method is undefined method. A class is Abstract class if at least one of
}
the methods is abstract.
Object Oriented Programming - CoSc2051 37 Object Oriented Programming - CoSc2051 38

Abstract Classes Abstract Classes


 If any other class inherits abstract class then that class also  Do’s and Don’ts of Abstract Class
becomes abstract class but to become a concrete class the  An Abstract class cannot be final because if it is made final then it

subclass must override the abstract method of super class. cannot be extended whereas abstract class is meant for
inheritance.
 A class becomes useful if it overrides all the methods of
 An Abstract method cannot be final because if it made final then it
abstract class
cannot be overridden whereas Abstract method is meant for
 Abstract classes are used for imposing standards and sharing overriding.
methods  Abstract Class and method can neither be final nor static.
 A Sub class must override an abstract method or else it will become
abstract class.

Object Oriented Programming - CoSc2051 39 Object Oriented Programming - CoSc2051 40


5/29/2023

Interfaces Interfaces
 Inheritance is used for borrowing methods.  In java a class can extend from one class only but if a class is implementing
 Abstract is used for achieving polymorphism as well as Inheritance. an interface then it can implement from multiple interfaces.
 Inheritance is completely used for achieving Polymorphism.  An interface in Java is a collection of abstract methods and static constants.
 Interface can be call as Abstract Class with all abstract methods.  As you might know in an interface, each method is public and abstract but it
 All the methods are by default abstract. does not contain any constructor.
 Classes are extended but Interfaces are implemented.  Along with abstraction, the interface also helps to achieve multiple
 In Interface we can have reference of interface and the object of the class inheritance in Java.
which is implemented.  Note:You can achieve 100% abstraction using interfaces.

Object Oriented Programming - CoSc2051 41 Object Oriented Programming - CoSc2051 42

Interfaces Interfaces
Interface
Example Program  Do’s and Don’ts of Interfaces
interface test1 {  By default, methods are Public and Abstract.
void meth1(); Collection of abstract  As methods are to be implemented by the classes, they can’t be made
method
void meth2(); private.
}
 Identifiers can be used in interfaces but the identifiers must be given in
class test2 implements test1 {
Implementation of
Upper cases.
public void meth1() {}
abstract method in  Identifiers are by default final and static.
public void meth2() {} derived class
}
 Method inside an interface cannot have body but the method can have

class test { body if the method is static.


public static void main(String[] args){ Creating an object derived  Static members can be accessed in main method by using interface name
class
test1 t=new test2 (); and dot operator.
t. meth1(); Calling method
} } Object Oriented Programming - CoSc2051 43 Object Oriented Programming - CoSc2051 44
5/29/2023

Interfaces Interface vs Abstract Class


 Do’s and Don’ts of Interfaces Interface Abstract Class

 An interface can be extended from another interface.  Can have Abstract and Non-Abstract
. Can have only Abstract Methods
Methods
 Interface VS Multiple Inheritance
 It has only Final Variables  It includes Non-Final Variables
 In C++ one class can inherit from multiple classes.
 It has Static, Non-Static, final, Non-
 Multiple Inheritance in java is achieved using Interfaces.  It has Static and Final variables only
Final variables
 Interfaces are perfect than using Multiple Inheritance.  Will not implement the Abstract
 Can implement an Interface
Class
 Way of thinking in java is more perfect than C++.
 Implemented using “implements”  Implemented using “extends”
Keyword Keyword
 Can extend Java Classes and
 Can extend only an Interface
Interfaces
 Members can be Private and
 Members are Public by default
Protected

Object Oriented Programming - CoSc2051 45 Object Oriented Programming - CoSc2051 46

Abstraction vs Encapsulation Bye


Abstraction Encapsulation

.  Solves the problem in the


 Solves the problem in design level
implementation level

 Encapsulation means hiding the


 Used for hiding unwanted data and code and data into a single unit to
giving relevant results. protect data from the outside
world

 Outer layout – used in terms of  Inner layout – used in terms of


Take a look :
design implementation
https://docs.oracle.com/en/java/

Object Oriented Programming - CoSc2051 47 Object Oriented Programming - CoSc2051 48

You might also like