SlideShare a Scribd company logo
1 of 37
INHERITANCE
Focus
• To explain inheritance concept,
• To apply inheritance concept in
programming.
• To list the types of accessibility modifier
INHERITANCE
• Inheritance let us to create a new class from the existing classes.
• The new class is called subclass and the existing class is called
superclass.
• The subclass inherits the properties of the superclass.
• The properties refer to the method or the attribute (data)
• Inheritance is ‘is-a’ relation
• Example : if a Circle inherits the Shape class, hence the Circle is
a Shape. (see the next figure)
What is Inheritance?
INHERITANCE
Box
Example
The class Circle and Rectangle are derived from Shape and the
class Box is derived from Rectangle.
Every Circle and every Rectangle is Shape and every Box is a
Rectangle
INHERITENCE
• If we need a new class with a same properties
or method of the current class, we do not need
to define a new class.
• A new class might be inherited from the
current class.
When it is used?
INHERITANCE
• Single inheritance
– Is a subclass that derived from a single/one superclass
(existing class)
• Multiple inheritance
– Is a subclass that derived from more than one superclass
– Not supported by Java
Types of Inheritances?
Geometry
Circle Triangle Square
Sphere Cone Cylinder Cubes
Single Inheritance
Multiple Inheritance
INHERITANCE
• Involve 2 classes :
– Super class.
– Sub class
Rectangle
Box
Super class
Sub class
Properties/Characteristics?
Super class and Sub class
Rectangle
double length
double width
Box
double height
INHERITANCE
• Super class – Rectangle
• Sub class – Box
• Attributes for Rectangle : length, width
• Attribute for Box : height
Box class inherits the length and
width of the Rectangle class
(superclass)
keyword extends
• extends is the keyword to implement inheritance in Java.
• Syntax
class SubClassName extends SuperClassName
{
// properties & methods
}
• E.g.
class Box extends Rectangle
{
// properties and coding
}
Rectangle
Box
INHERITANCE
public class Rectangle
{
private double length;
private double width;
public Rectangle()
{
length = 0;
width = 0;
}
public Rectangle(double L, double W)
{
setDimension(L,W);
}
public void setDimension(double L, double W)
{
if (L >= 0)
length = L;
else
length = 0;
if (W >= 0)
width = W;
else
width = 0;
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public double area()
{
return length * width;
}
public void print()
{
System.out.print(“length = “ + length);
System.out.print(“width = “ + width);
}
} // end for Rectangle class
E.g. : Rectangle class
Rectangle
- length : double
- width : double
+ Rectangle()
+ Rectangle(double,double)
+ setDimension(double,double) : void
+ getLength() : double
+ getWidth() : double
+ area() : double
+ print() : void
The class Rectangle has 9 members
UML class diagram of the Rectangle class
public class Box extends Rectangle
{
private double height;
public Box()
{
super();
height = 0;
}
public Box(double L, double W, double H)
{
super(L,W);
height = H;
}
public void setDimension(double L, double W, double H)
{
setDimension(L,W);
if (H >= 0)
height = H;
else
height = 0;
}
public double getHeight()
{
return height;
}
public double area()
{
return 2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height);
}
public double volume()
{
return super.area() * height;
}
public void print()
{
super.print();
system.out.print(“height = “ + height);
}
} // end for class Box extends
E.g. : Box class
Box
- height : double
- length : double (can’t access directly)
- width : double (cant’ access directly)
+ Box()
+ Box(double,double)
+ setDimension(double,double) : void
+ setDimension(double,double,double) : void (overloads parent’s setDimension())
+ getLength() : double
+ getWidth() : double
+ getHeight() : double
+ area() : double (overrides parent’s area())
+ volume() : double
+ print() : void (overrides parent’s print())
The class Box has 13 members
UML class diagram of the class Box
• The class Box is derived from the class Rectangle
• Therefore, all public members of Rectangle are public members of Box
• The class Box overrides the method print and area
• The class Box has 3 data members : length, width and height
• The instance variable length and width are private members of the class
Rectangle
• So, it cannot be directly accessed in class Box
• Use the super keyword to call a method of the superclass.
• To print the length and width, a reserve word super should be put into the print
method of class Box to call the parent’s print() method.
• The same case happen in the volume method where super.area() is being used to
determine the base area of box.
• The method area of the class Box determines the surface area of the box.
• To retrieve the length and width, the methods getLength and getWidth in class
Rectangle is being used.
• Here, the reserve word super is not used because the class Box does not override
the methods getLength and getWidth
Defining Classes with Inheritance
• Case Study:
– Suppose we want implement a class roster that
contains both undergraduate and graduate students.
– Each student’s record will contain his or her name, three
test scores, and the final course grade.
– The formula for determining the course grade is
different for graduate students than for undergraduate
students.
Undergrads: pass if avg test score >= 70
Grads: pass if avg test score >= 80
Modeling Two Types of Students
• There are two ways to design the classes to
model undergraduate and graduate
students.
– We can define two unrelated classes, one for
undergraduates and one for graduates.
– We can model the two kinds of students by using
classes that are related in an inheritance hierarchy.
• Two classes are unrelated if they are not
connected in an inheritance relationship.
Classes for the Class Roster
• For the Class Roster sample, we design three classes:
– Student
– UndergraduateStudent
– GraduateStudent
• The Student class will incorporate behavior and data
common to both UndergraduateStudent and
GraduateStudent objects.
• The UndergraduateStudent class and the
GraduateStudent class will each contain behaviors and
data specific to their respective objects.
Inheritance Hierarchy
+ computeCourseGrade() : int + computeCourseGrade() : int
+ computeCourseGrade() : int
+ UndergraduateStudent() : void + GraduateStudent() : void
Definition of GraduateStudent &
UndergraduateStudent classes
class GraduateStudent extends Student {
//constructor not shown
public void computeCourseGrade() {
int total = 0;
total = test1 + test2 + test3;
if (total / 3 >= 80) {
courseGrade = "Pass";
} else {
courseGrade = "No Pass";
}
}
}
class UndergraduateStudent extends Student {
//Constructor not shown
public void computeCourseGrade() {
int total = 0;
total = test1 + test2 + test3;
if (total / 3 >= 70) {
courseGrade = "Pass";
} else {
courseGrade = "No Pass";
}
}
}
Declaring a Subclass
A subclass inherits data and methods from the
superclass. In the subclass, you can also:
Add new data
Add new methods
Override the methods of the superclass
Modify existing behaviour of parent
Overriding vs. Overloading
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
}
}
class B {
public void p(int i) {
}
}
class A extends B {
// This method overrides the method in B
public void p(int i) {
System.out.println(i);
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
}
}
class B {
public void p(int i) {
}
}
class A extends B {
// This method overloads the method in B
public void p(double i) {
System.out.println(i);
}
}
Inheritance Rules
1. The private members of the superclass are
private to the superclass
2. The subclass can access the members of the
superclass according to the accessibility rules
3. The subclass can include additional data and/or
method members
Inheritance Rules (continued)
4. The subclass can override, that is, redefine
the methods of the superclass
The overriding method in subclass must have similar
Name
Parameter list
Return type
5. All members of the superclass are also
members of the subclass
– Similarly, the methods of the superclass (unless
overridden) are also the methods of the subclass
– Remember Rule 1 & 2 when accessing a member
of the superclass in the subclass
• To call a superclass constructor
– super(); //must be the first statement in subclass’s constructor
• To call a superclass method
– super.methodname();
– this is only used if the subclass overrides the superclass
method
6. (Using the Keyword super)
The keyword super refers to the direct
superclass of a subclass . This keyword can
be used in two ways:
Inheritance Rules (continued)
The Object Class is the Superclass of Every
Java Class
(Accessibility Modifier)
• Sometimes , it is called visibility modifier
• Not all properties can be accessed by sub class.
• Super class can control a data accessing from subclass
by giving the type of accessing to the members and
methods.
• A class can declare the data members or method as a
public, private or protected.
• If it is not declared, the data or method will be set to
default type.
INHERITANCE
Accessibility criteria
Modifier Same Class Same
Package
Subclass Universe
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
Member Accessibility
INHERITANCE
Sub class B
public int b
protected int c
Super class
int a
public int b
protected int c
private int d
Sub class A
int a
public int b
protected int c
Package B
Package A
Data Accessibility
INHERITANCE
Refer to the previous slide
• Super class has 2 subclasses : Subclass A and
Subclass B.
• Subclass A is defined in same package with
superclass, subclass B is defined outside the
package.
• There are 4 accessibility data types: public, protected,
private and default.
• Subclass A can access all properties of superclass
except private.
• But, subclass B can only access the properties outside
the package which are public and protected.
Example: Visibility Modifiers
public class C1 {
public int x;
protected int y;
int z;
private int u;
protected void m() {
}
}
public class C2 {
C1 o = new C1();
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
can invoke o.m();
}
public class C3
extends C1 {
can access x;
can access y;
can access z;
cannot access u;
can invoke m();
}
package p1;
public class C4
extends C1 {
can access x;
can access y;
cannot access z;
cannot access u;
can invoke m();
}
package p2;
public class C5 {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;
cannot invoke o.m();
}
What’s
wrong with
the code?
How to fix
it?
class ClassX
{
private int m;
public String toString()
{
return new String("(" + m + ")");
}
}
public class ClassY extends ClassX
{
private int n;
public String toString()
{
return new String("(" + m + " , " + n + ")");
}
}
class TestAccesibility
{
public static void main(String [] args)
{
ClassX x = new ClassX;
ClassY y = new ClassY;
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
Inheritance and Constructors
• Unlike members of a superclass, constructors of a
superclass are not inherited by its subclasses.
• You must define a constructor for a class or use
the default constructor added by the compiler.
• The statement
super();
calls the superclass’s constructor.
• super(); must be the first statement in the
subclass contructor.
public Box(double l, double w, double h)
{
super(l,w);
height = h;
}
• A call to the constructor of the superclass
must be in the first statement in the child
constructor.
Rectangle myRectangle = new Rectangle(5, 3);
Box myBox = new Box(6, 5, 4);
Superclass’s Constructor Is Always Invoked
A subclass constructor may invoke its superclass’s
constructor. If none is invoked explicitly, the compiler
puts super() as the first statement in the constructor.
For example, the constructor of class A:
public A(double d) {
// some statements
}
is equivalent to
public A(double d) {
super();
// some statements
}
public A() {
}
is equivalent to
public A() {
super();
}
Example on the Impact of a Superclass without no-arg
Constructor
class Fruit {
public Fruit(String name) {
System.out.println("Fruit constructor is invoked");
}
}
public class Apple extends Fruit {
public Apple(String name) {
System.out.println(“Apple constructor is invoked");
}
}
Find out the error in the program:

More Related Content

What's hot

Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196Mahmoud Samir Fayed
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84Mahmoud Samir Fayed
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in javaAtul Sehdev
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods javaPadma Kannan
 
Java Inheritance | Java Course
Java Inheritance | Java Course Java Inheritance | Java Course
Java Inheritance | Java Course RAKESH P
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introductionSohanur63
 

What's hot (20)

Ch03
Ch03Ch03
Ch03
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
OOP Inheritance
OOP InheritanceOOP Inheritance
OOP Inheritance
 
The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
 
Java Inheritance | Java Course
Java Inheritance | Java Course Java Inheritance | Java Course
Java Inheritance | Java Course
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 

Viewers also liked

abitha-pds inheritance presentation
abitha-pds inheritance presentationabitha-pds inheritance presentation
abitha-pds inheritance presentationabitha ben
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritanceNurhanna Aziz
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)farhan amjad
 
169 Ch 29_lecture_presentation
 169 Ch 29_lecture_presentation 169 Ch 29_lecture_presentation
169 Ch 29_lecture_presentationgwrandall
 

Viewers also liked (9)

Lecture4
Lecture4Lecture4
Lecture4
 
abitha-pds inheritance presentation
abitha-pds inheritance presentationabitha-pds inheritance presentation
abitha-pds inheritance presentation
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritance
 
Opps
OppsOpps
Opps
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
 
Inheritance
InheritanceInheritance
Inheritance
 
169 Ch 29_lecture_presentation
 169 Ch 29_lecture_presentation 169 Ch 29_lecture_presentation
169 Ch 29_lecture_presentation
 
Inheritance
InheritanceInheritance
Inheritance
 

Similar to Inheritance & Polymorphism - 1

Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritanceKalai Selvi
 
Chapter 8.1
Chapter 8.1Chapter 8.1
Chapter 8.1sotlsoc
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxVikash Dúbēy
 
Intro To C++ - Class #22: Inheritance, Part 1
Intro To C++ - Class #22: Inheritance, Part 1Intro To C++ - Class #22: Inheritance, Part 1
Intro To C++ - Class #22: Inheritance, Part 1Blue Elephant Consulting
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
Unit 7 inheritance
Unit 7 inheritanceUnit 7 inheritance
Unit 7 inheritanceatcnerd
 
.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloadingDrRajeshreeKhande
 

Similar to Inheritance & Polymorphism - 1 (20)

Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Chapter 8.1
Chapter 8.1Chapter 8.1
Chapter 8.1
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
Intro To C++ - Class #22: Inheritance, Part 1
Intro To C++ - Class #22: Inheritance, Part 1Intro To C++ - Class #22: Inheritance, Part 1
Intro To C++ - Class #22: Inheritance, Part 1
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
 
Unit 7 inheritance
Unit 7 inheritanceUnit 7 inheritance
Unit 7 inheritance
 
.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
Core java oop
Core java oopCore java oop
Core java oop
 

More from PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2PRN USM
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - IntroPRN USM
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition StructurePRN USM
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control StructuresPRN USM
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And ExpressionPRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and JavaPRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree HomesPRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean ExperiencePRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesPRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlPRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From MhpbPRN USM
 

More from PRN USM (19)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Array
ArrayArray
Array
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

Inheritance & Polymorphism - 1

  • 2. Focus • To explain inheritance concept, • To apply inheritance concept in programming. • To list the types of accessibility modifier
  • 3. INHERITANCE • Inheritance let us to create a new class from the existing classes. • The new class is called subclass and the existing class is called superclass. • The subclass inherits the properties of the superclass. • The properties refer to the method or the attribute (data) • Inheritance is ‘is-a’ relation • Example : if a Circle inherits the Shape class, hence the Circle is a Shape. (see the next figure) What is Inheritance?
  • 4. INHERITANCE Box Example The class Circle and Rectangle are derived from Shape and the class Box is derived from Rectangle. Every Circle and every Rectangle is Shape and every Box is a Rectangle
  • 5. INHERITENCE • If we need a new class with a same properties or method of the current class, we do not need to define a new class. • A new class might be inherited from the current class. When it is used?
  • 6. INHERITANCE • Single inheritance – Is a subclass that derived from a single/one superclass (existing class) • Multiple inheritance – Is a subclass that derived from more than one superclass – Not supported by Java Types of Inheritances?
  • 7. Geometry Circle Triangle Square Sphere Cone Cylinder Cubes Single Inheritance Multiple Inheritance
  • 8. INHERITANCE • Involve 2 classes : – Super class. – Sub class Rectangle Box Super class Sub class Properties/Characteristics?
  • 9. Super class and Sub class Rectangle double length double width Box double height INHERITANCE • Super class – Rectangle • Sub class – Box • Attributes for Rectangle : length, width • Attribute for Box : height Box class inherits the length and width of the Rectangle class (superclass)
  • 10. keyword extends • extends is the keyword to implement inheritance in Java. • Syntax class SubClassName extends SuperClassName { // properties & methods } • E.g. class Box extends Rectangle { // properties and coding } Rectangle Box INHERITANCE
  • 11. public class Rectangle { private double length; private double width; public Rectangle() { length = 0; width = 0; } public Rectangle(double L, double W) { setDimension(L,W); } public void setDimension(double L, double W) { if (L >= 0) length = L; else length = 0; if (W >= 0) width = W; else width = 0; } public double getLength() { return length; } public double getWidth() { return width; } public double area() { return length * width; } public void print() { System.out.print(“length = “ + length); System.out.print(“width = “ + width); } } // end for Rectangle class E.g. : Rectangle class
  • 12. Rectangle - length : double - width : double + Rectangle() + Rectangle(double,double) + setDimension(double,double) : void + getLength() : double + getWidth() : double + area() : double + print() : void The class Rectangle has 9 members UML class diagram of the Rectangle class
  • 13. public class Box extends Rectangle { private double height; public Box() { super(); height = 0; } public Box(double L, double W, double H) { super(L,W); height = H; } public void setDimension(double L, double W, double H) { setDimension(L,W); if (H >= 0) height = H; else height = 0; } public double getHeight() { return height; } public double area() { return 2 * (getLength() * getWidth() + getLength() * height + getWidth() * height); } public double volume() { return super.area() * height; } public void print() { super.print(); system.out.print(“height = “ + height); } } // end for class Box extends E.g. : Box class
  • 14. Box - height : double - length : double (can’t access directly) - width : double (cant’ access directly) + Box() + Box(double,double) + setDimension(double,double) : void + setDimension(double,double,double) : void (overloads parent’s setDimension()) + getLength() : double + getWidth() : double + getHeight() : double + area() : double (overrides parent’s area()) + volume() : double + print() : void (overrides parent’s print()) The class Box has 13 members UML class diagram of the class Box
  • 15. • The class Box is derived from the class Rectangle • Therefore, all public members of Rectangle are public members of Box • The class Box overrides the method print and area • The class Box has 3 data members : length, width and height • The instance variable length and width are private members of the class Rectangle • So, it cannot be directly accessed in class Box • Use the super keyword to call a method of the superclass. • To print the length and width, a reserve word super should be put into the print method of class Box to call the parent’s print() method. • The same case happen in the volume method where super.area() is being used to determine the base area of box. • The method area of the class Box determines the surface area of the box. • To retrieve the length and width, the methods getLength and getWidth in class Rectangle is being used. • Here, the reserve word super is not used because the class Box does not override the methods getLength and getWidth
  • 16. Defining Classes with Inheritance • Case Study: – Suppose we want implement a class roster that contains both undergraduate and graduate students. – Each student’s record will contain his or her name, three test scores, and the final course grade. – The formula for determining the course grade is different for graduate students than for undergraduate students. Undergrads: pass if avg test score >= 70 Grads: pass if avg test score >= 80
  • 17. Modeling Two Types of Students • There are two ways to design the classes to model undergraduate and graduate students. – We can define two unrelated classes, one for undergraduates and one for graduates. – We can model the two kinds of students by using classes that are related in an inheritance hierarchy. • Two classes are unrelated if they are not connected in an inheritance relationship.
  • 18. Classes for the Class Roster • For the Class Roster sample, we design three classes: – Student – UndergraduateStudent – GraduateStudent • The Student class will incorporate behavior and data common to both UndergraduateStudent and GraduateStudent objects. • The UndergraduateStudent class and the GraduateStudent class will each contain behaviors and data specific to their respective objects.
  • 19. Inheritance Hierarchy + computeCourseGrade() : int + computeCourseGrade() : int + computeCourseGrade() : int + UndergraduateStudent() : void + GraduateStudent() : void
  • 20. Definition of GraduateStudent & UndergraduateStudent classes class GraduateStudent extends Student { //constructor not shown public void computeCourseGrade() { int total = 0; total = test1 + test2 + test3; if (total / 3 >= 80) { courseGrade = "Pass"; } else { courseGrade = "No Pass"; } } } class UndergraduateStudent extends Student { //Constructor not shown public void computeCourseGrade() { int total = 0; total = test1 + test2 + test3; if (total / 3 >= 70) { courseGrade = "Pass"; } else { courseGrade = "No Pass"; } } }
  • 21. Declaring a Subclass A subclass inherits data and methods from the superclass. In the subclass, you can also: Add new data Add new methods Override the methods of the superclass Modify existing behaviour of parent
  • 22. Overriding vs. Overloading public class Test { public static void main(String[] args) { A a = new A(); a.p(10); } } class B { public void p(int i) { } } class A extends B { // This method overrides the method in B public void p(int i) { System.out.println(i); } } public class Test { public static void main(String[] args) { A a = new A(); a.p(10); } } class B { public void p(int i) { } } class A extends B { // This method overloads the method in B public void p(double i) { System.out.println(i); } }
  • 23. Inheritance Rules 1. The private members of the superclass are private to the superclass 2. The subclass can access the members of the superclass according to the accessibility rules 3. The subclass can include additional data and/or method members
  • 24. Inheritance Rules (continued) 4. The subclass can override, that is, redefine the methods of the superclass The overriding method in subclass must have similar Name Parameter list Return type 5. All members of the superclass are also members of the subclass – Similarly, the methods of the superclass (unless overridden) are also the methods of the subclass – Remember Rule 1 & 2 when accessing a member of the superclass in the subclass
  • 25. • To call a superclass constructor – super(); //must be the first statement in subclass’s constructor • To call a superclass method – super.methodname(); – this is only used if the subclass overrides the superclass method 6. (Using the Keyword super) The keyword super refers to the direct superclass of a subclass . This keyword can be used in two ways: Inheritance Rules (continued)
  • 26. The Object Class is the Superclass of Every Java Class
  • 27. (Accessibility Modifier) • Sometimes , it is called visibility modifier • Not all properties can be accessed by sub class. • Super class can control a data accessing from subclass by giving the type of accessing to the members and methods. • A class can declare the data members or method as a public, private or protected. • If it is not declared, the data or method will be set to default type. INHERITANCE
  • 28. Accessibility criteria Modifier Same Class Same Package Subclass Universe private Yes No No No default Yes Yes No No protected Yes Yes Yes No public Yes Yes Yes Yes Member Accessibility INHERITANCE
  • 29. Sub class B public int b protected int c Super class int a public int b protected int c private int d Sub class A int a public int b protected int c Package B Package A Data Accessibility INHERITANCE
  • 30. Refer to the previous slide • Super class has 2 subclasses : Subclass A and Subclass B. • Subclass A is defined in same package with superclass, subclass B is defined outside the package. • There are 4 accessibility data types: public, protected, private and default. • Subclass A can access all properties of superclass except private. • But, subclass B can only access the properties outside the package which are public and protected.
  • 31. Example: Visibility Modifiers public class C1 { public int x; protected int y; int z; private int u; protected void m() { } } public class C2 { C1 o = new C1(); can access o.x; can access o.y; can access o.z; cannot access o.u; can invoke o.m(); } public class C3 extends C1 { can access x; can access y; can access z; cannot access u; can invoke m(); } package p1; public class C4 extends C1 { can access x; can access y; cannot access z; cannot access u; can invoke m(); } package p2; public class C5 { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; cannot access o.u; cannot invoke o.m(); }
  • 32. What’s wrong with the code? How to fix it? class ClassX { private int m; public String toString() { return new String("(" + m + ")"); } } public class ClassY extends ClassX { private int n; public String toString() { return new String("(" + m + " , " + n + ")"); } } class TestAccesibility { public static void main(String [] args) { ClassX x = new ClassX; ClassY y = new ClassY; System.out.println("x = " + x); System.out.println("y = " + y); } }
  • 33. Inheritance and Constructors • Unlike members of a superclass, constructors of a superclass are not inherited by its subclasses. • You must define a constructor for a class or use the default constructor added by the compiler. • The statement super(); calls the superclass’s constructor. • super(); must be the first statement in the subclass contructor.
  • 34. public Box(double l, double w, double h) { super(l,w); height = h; } • A call to the constructor of the superclass must be in the first statement in the child constructor.
  • 35. Rectangle myRectangle = new Rectangle(5, 3); Box myBox = new Box(6, 5, 4);
  • 36. Superclass’s Constructor Is Always Invoked A subclass constructor may invoke its superclass’s constructor. If none is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example, the constructor of class A: public A(double d) { // some statements } is equivalent to public A(double d) { super(); // some statements } public A() { } is equivalent to public A() { super(); }
  • 37. Example on the Impact of a Superclass without no-arg Constructor class Fruit { public Fruit(String name) { System.out.println("Fruit constructor is invoked"); } } public class Apple extends Fruit { public Apple(String name) { System.out.println(“Apple constructor is invoked"); } } Find out the error in the program: