SlideShare a Scribd company logo
Chapte
r
Thre
e
Inheritan
ce u
1
0
What Is Inheritance?
In the real world: we inherit traits from our
motheran
d
father
.
We als
o
inherit traits from
We
our
migh
t
grandmothe
r,
grandfathe
r,
an
d
ancestor
s.have similar eyes, the
same
smile,A different
height.
But we are in many ways "derived" from our
parents.
In software: object inheritance is more well
defined!
Objects that are derived
from
other
both
object
"resemble"their parent
s
by inheritin
g
stat
e
(fields
)
an
dbehavior
(methods). 2
uu )
Contd
.Inheritanc
e
is A fundament
al
featur
e
of object-
orientedprogrammin
g
whic
h
enable
s
the
programmer
to write A
class based on an already existing
class.
Th
e
already existin
g
clas
s
is calle
d
the paren
t
clas
s,
or
orsuperclas
s,
and the ne
w
clas
s
is calle
d
the subclas
s,derived
class.
Th
e
subclass
inherits
(reuse
s)
the no
n
private member
s(methods and variables) of
the
its own members as well.
superclass, and may
define
Inheritance
extends.
 When class b is a subcla
uss o
uf class a, we say b
is
implemented
in java usin
g
the keywor
d
3
)
Advantages Of
Inheritance.Cod
e
reusabilit
y:-
inheritan
ce
automates the
process
of
reusing the code of the superclasses in the
subclasses.
 With inheritance, an object can inherit its more general properties
from its
paren
t
object
,
and that save
s
th
e
redundanc
y
in
programmin
g.
Cod
e
maintenan
ce:-
organizin
g
cod
e
int
o
hierarchic
alclasses makes its maintenance and management
easier.
Implement
ing
OOP:-
inheritance
help
s
to impleme
nt
th
ebasic 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.
4
uu )
Inheritance
TypesA.
Single
level
inheritance:-
inheritance
in
super class.
which a
class inherits from only
one
B. Multi-
level
inheritance:
-
inheritanc
e
in which a
class inherits from a class which itself inherits
from
another class.Here a minimum of
three
classes is
required.
here two or more

C. Hierarchy
inheritance:-
inherits from one class.
D. Multiple inheritance:-
a
more classes.
classe
s
class inherits
from
two or
This type of inheritance is not supported in
java.

5
)
Dog
Class
public class Dog {
private String name;private int fleas;
public Dog(string n, int f) {
name =
fleas =
n;
f;
}
public
public
public
String getName() { return name; }
int getFleas() { return fleas; }
void speak() {
System.out.println("woof");
}
} 6
uu )
CAT
CLASSpublic class Cat {
private string name;
private int hairBalls;
public Cat(string n, int
name = n;
hairballs = h;
}
h) {
public
public
public
String getName() { return name; }
int getHairBalls() { return
void speak() {
hairballs; }
System.out.println("meow");
}
} 7
uu )
Problem: Code
Duplication
Dog and Cat have the name field and
the
getName method in common
Classes
often
in common
have a lot of
state
and behavio
r
Resul
t:
lot
s
of duplicate
code!
8
uu )
Solution:
Inheritance
Inheritance allows you to write new classes that
inherit
from existing classes
The existing class whose properties are inherited is
called
the "parent" or superclassThe new class that
inherits
the "child" or subclass
Result: lots of code
reuse!
from the supe
r
clas
s
is calle
d
9
uu )
using
inheritance
superclass
subclass
subclass
10
)
Dog
int fleas int
getFleas()
void speak() uu
Cat
int hairballs int
getHairballs()
voidspeak()
Animal String
name String
getName()
Cat String
name int
hairballs
String getName()
int getHairballs()
voidspeak()
Dog String
name int
fleas
String getName()
int getFleas()
void speak()
Animal
Superclass
public
{
class Animal
private String name;
public Animal(string n) {
name = n;
}
public String getName() {
return name;
}
}
11
uu )
Dog
Subclass
public class Dog extends Animal {
private int fleas;
public Dog(string n, int f) {
super(n); // calls animal
fleas = f;
constructor
}
public int getFleas()
return fleas;
}
{
public void speak() {
return System.out.println("woof");
}
uu
} 12
)
Cat
Subclass
public class Cat extends Animal {
private int hairballs;
public Cat(string n, int h) {
super(n); // calls animal
hairballs = h;
constructor
}
public int getHairBalls() {
return hairballs;
}
public void speak() {
return System.out.println("meow");
}
} 13
uu )
Inheritance
Quiz
1
• What is the output of the
following?Dog d
Cat c
=
=
new Dog("rover" 3);
new Cat("kitty", 2);
System.out.println(d.getName() + " has " +
d.getFleas() + " fleas");
System.out.println(c.getName() + " has " +
c.getHairBalls() + " hairballs");
rover has 3 fleas
kitty has 2
hairballs
14
(Dog and Cat inherit the ge
utN
uame method from
)
Inheritance
Rules
Us
e
the extends keyword to indicat
e
that one clas
sinherits from another
The subclass inherits all the nonprivate fields and
methods of the superclass
Use the super keyword
in
the subclas
s
constructor to cal
lthe superclas
s
constructor
15
uu )
Subclass
Constructor
• The first thing a subclass constructor must do is
call
the superclass constructor.
• This ensures that the superclass part of the
object is
constructed before the subclass part
• If you do not call the superclass constructor with
the super keyword, and the superclass has a
constructor with no arguments, then that
superclass
16
uu )
Implicit Supe
r
Constructor
Call
then this Beef subclass:
public class Beef extends Food
private double weight;
public Beef(double w) {
weight = w
}
}
{
if I have this food
class:
public class food
{
private boolean
public food() {
raw = true;
}
}
raw;
is equivalent to:
public class Beef extends Food
private double weight;
public Beef(double w) {
super();
weight = w
{
17
}
u}u )
Inheritance Quiz
2public class
public A()
}
A
{
{
System.out.println("I'm A"); }
public class
public B()
}
B
{
extends A {
System.out.println("I'm B"); }
public class
public C()
}
C
{
extends B {
System.out.println("I'm C"); }
What does this print out? I'm
I'm
I'm
A
B
CC x = new C(); 18
uu )
Overriding
Methods When a
method
type signature
as
method is said
to
in a super class has the same name as
and
a method in the superclass, then the
subclass
override the method in the superclass.
 During overriding a method the following takes place:
 The new method overrides (and hides) the original
method.
 When you override a method, you can call the
superclass's
copy of the method by using the syntax
super.method().
 You can not do super.super. to back up two levels.
 You canno
t
chang
e
the return type whe
n
overridin
g
impossibl
e.
a
method, since this would make
polymorphism
uu )
class MyDerived extends
{
int y;
MyBase
class MyBase
{
private int
public MyDerived(int
{
super(x);
}
public MyDerived(int
{
super(x);
x)
x;
public MyBase(int
{
x)
x, int y)
this.x
}
= x;
public
{
return
}
public
{
int getX()
this.y
}
public
{
return
}
public
{
= y;
x;
int getY()
void show()
y;
System.out.println("x="
}
}
+ x);
void show()
super.show();
System.out.println("y = " + y);
} 20
uu}
)
Final Variables, Methods
And
Class
es All methods and
variables
in subclasses.
can be overridden by
default

Use
th
e
fin
al
keywor
d
member
s
to
of
preven
t
th
e
subclass
es
from
overriding
the
Example:
final
th
e
superclas
s. This method
will not be
overridden
int num=10;
public final void show()
{
System.out.println("x=" +
}
x);
 It is also possible to define a class as final
if we
class not to be inherited.
 Any attempt to inherit a final class will
cause
wan
t
th
e
an
error 21
)
Abstract Classes
An abstract method is a method that is declared
without implementation .
an
Exampl
e:
abstract void display();
An abstrac
t
clas
s
is a clas
s
that is incomplet
e,
or to be
considered incomplete.
Only abstract classes may have abstract
methods, that
is
,

methods that are declared but not yet implemented
and non
abstract methods.
An abstract class may or may not contain abstract
methods.
An abstract class is a class that cannot be
instantiated, we


cannot create instances of
uan
uabstract
22
)
Contd.
While using abstract classes:
 We cannot use abstract
classes
directly.
to instantiate
objects

The
abstract method
of
an
abstract
clas
s
mus
t
be
defined in its
subclass.
 We cannot
declare
abstract constructors
or
abstrac
tstatic methods.
 Abstract classes
can
methods and one
or
have none, one or
more
abstrac
tmore non abstract
methods. 23
)
abstract class A
{
abstract void callme(); // abstract method
void callmetoo() // Non-abstract method
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void callme() //Implementation of super class’s
{
abstract method
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[]) {
A
A
B
ab;// possible
ab1=new A();
b = new B();
// Is not correct
b.callme();
b.callmetoo(); 24
uu}
}
)
Visibility Control (Access Level)
 By using inheritance it is possible to inherit all members
of the superclass being on the subclasses.
 But it is also possible to
restrict
from outside the class. This s
done
the access of certain
fields
using access modifiers.

Classes
can contain
fields
and method
s
of four different
access
levels:
A.
private:-
private variable
s
and method
s
are accessibl
ewithin their own class (access only to
the class
itself)
.
B. Friendly access:- when no access modifier is
specified, themembers’ are access only to classes in
the same
No access level is specified in this
case.
package
.
25
)
Contd.
C. protected:- makes the fields visible to all
classes andsubclasses
within
th
e
sam
e
package and
to
all
subclasses from other
packages.
D.
Private
protecte
d:-
make
s
th
e
fields visible
in
all
subclasses regardless of what package they
are in.
These fields are not accessible by other
classes in
the same package.
E. public:- These variables or methods have
access to all
classes everywhere.
26
such
members.
u
))
Programming Example
A company has a list of employees. It asks you to
provide a
payroll sheet for all employees.
Has extensive data (name, department,
pay
employees.
amount, …) for
all
Different types
engineer.
You have an old employee class but
need to
of employee
s
– manager
,
enginee
r,
softwar
e
add very different
data and methods for managers and
engineers. Suppose
someone
wrote a nam
e
syste
m,
and already
provided a legacy employee class.
 The old employee class had a printData()
method
for
eachemployee that only printed the name. We want to reuse
it, and
27
uuprint pay
info. )
Review
PictureMessage passing "Main event loop"Encapsulation
Employee e1
private:
lastName
firstName
uu )
printData
public … Main(…){
Employee e1…("Mary","Wang");
...
e1.printData();
// Prints Employee names.
...
}
28
Employee
class
//This is a simpler super class
class Employee {
// Data
private String firstName, lastName;
// Constructor
public Employee(String fName, String lName) {
firstName= fName; lastName= lName;
}
// Method
public void printData() {
System.out.println(firstName + " " + lastName);}
}
29
uu )
Inheritance
Diagram
Already written:
Class Employee printData()firstName
lastName
is-a
Class Engineer
is-a
Class Manager
firstName
lastName
firstName
lastName
hoursWorked
salary
wagesprintData()
getPay()
printData()
getPay()
30
You
une
uxt write:
)
Engineer Class
//A subclass derived from Employee class
class Engineer extends Employee {
private double wage;
private double hoursWorked;
public Engineer(String fName, String lName,
double rate, double
super(fName, lName);
wage = rate;
hoursWorked = hours;
hours) {
}
public double getPay() {
return wage * hoursWorked;
}
public void printData() {
super.printData();
System.out.println("Weekly
uu
// PRINT NAME
pay: Birr" + getPay();
31
}
}
)
Manager
Class
//A subclass derived from Employee class
class Manager extends Employee {
private double salary;
public Manager(String fName,
super(fName, lName);
salary = sal; }
String lName, double sal){
public double getPay() {
return salary; }
public void printData() {
super.printData();
System.out.println("Monthly salary: Birr" + salary);}
}
32
uu )
Inheritance
…
Class Manager
firstName
lastName
is-a
Salary
Class SalesManager
firstName
lastName
Salary
getPay
u
33
u salesBonus
)
printData
printData
getPay
Sales Manager
Class
//A subclass derived from Manager class
class SalesManager extends Manager {
private double salesBonus;
commission.
// Bonus Possible as
// A SalesManager gets a constant
public SalesManager(String fName,
super(fName, lName, 1250.0);
salesBonus = b; }
salary
String
of $1250.0
lName, double b) {
public double getPay() {
return 1250.0; }
public void printData() {
super.printData();
System.out.println("Bonus Pay:
uu
$" + salesBonus; }
34
}
)
Main
Method
public class PayRoll {
public static void main(String[] args) {
// Object creation and Initialization (Using constructors)
Engineer fred
Manager ann
= new Engineer("Fred", "Smith", 12.0, 8.0);
= new Manager("Ann", "Brown", 1500.0);
SalesManager mary= new SalesManager("Mary", "Kate", 2000.0);
// Polymorphism, or late binding
Employee[] employees = new Employee[3];
employees[0]=
employees[1]=
employees[2]=
fred;
ann;
mary;
System.out.println(“===========================“);
for (int i=0; i < 3; i++)
employees[i].printData();
System.out.println(“===========================“);
}
uu
35
}
)
Output from Main
===========================
Fred Smith
Weekly pay: $96.0
Ann Brown
Monthly salary: $1500.0
Mary Barrett
Monthly salary: $1250.0
Bonus: $2000.0
===========================
Note that we could not write:
employees[i].getPay();
Method
becaus
e
getPay(
)
is no
t
a metho
d
of th
e
supercla
ssEmployee.
In contrast, printData() is a
method of
can find the appropriate version.
Employee, so
Java
36
)
Object Class
All java classes implicitly inherit from
java.lang.Object
So every class you write will automatically have
methods in
object such as equals, and toString etc.
We'll learn
about
the importanc
e
of som
e
of thes
e
methods
inlater lectures
.
37
uu )

More Related Content

What's hot

Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.
MASQ Technologies
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
Java session4
Java session4Java session4
Java session4
Jigarthacker
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
Ahsan Raja
 
EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++
Nikunj Patel
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
Inheritance
InheritanceInheritance
Inheritance
Tech_MX
 
javainheritance
javainheritancejavainheritance
javainheritance
Arjun Shanka
 
Inheritance in java
Inheritance in javaInheritance in java
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Inheritance
InheritanceInheritance
Inheritance
poonam.rwalia
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
sotlsoc
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
sushamaGavarskar1
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
BHUVIJAYAVELU
 
Inheritance
InheritanceInheritance
Inheritance
Loy Calazan
 
Friend functions
Friend functions Friend functions
Friend functions
Megha Singh
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
Svetlin Nakov
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
RAJ KUMAR
 

What's hot (20)

Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Java session4
Java session4Java session4
Java session4
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Inheritance
InheritanceInheritance
Inheritance
 
javainheritance
javainheritancejavainheritance
javainheritance
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Friend functions
Friend functions Friend functions
Friend functions
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 

Similar to Oop inheritance chapter 3

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
Sunil Kumar Gunasekaran
 
Java
JavaJava
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
Presentation 3.pdf
Presentation 3.pdfPresentation 3.pdf
Presentation 3.pdf
JatinGupta645530
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
JayMistry91473
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
Rosie Jane Enomar
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
Atul Sehdev
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
ASHNA nadhm
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
Rassjb
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Inheritance
InheritanceInheritance
Inheritance
SangeethaSasi1
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
ParikhitGhosh1
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
Chap11
Chap11Chap11
Chap11
Terry Yoast
 
Inheritance
InheritanceInheritance
Inheritance
JayanthiNeelampalli
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
WaqarRaj1
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
LadallaRajKumar
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
Nivegeetha
 

Similar to Oop inheritance chapter 3 (20)

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
 
Java
JavaJava
Java
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Presentation 3.pdf
Presentation 3.pdfPresentation 3.pdf
Presentation 3.pdf
 
Core java oop
Core java oopCore java oop
Core java oop
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Inheritance
InheritanceInheritance
Inheritance
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Chap11
Chap11Chap11
Chap11
 
Inheritance
InheritanceInheritance
Inheritance
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
 

More from Narayana Swamy

AICTE GUIDLINES AICTE GUIDLINESAICTE GUIDLINES
AICTE GUIDLINES  AICTE GUIDLINESAICTE GUIDLINESAICTE GUIDLINES  AICTE GUIDLINESAICTE GUIDLINES
AICTE GUIDLINES AICTE GUIDLINESAICTE GUIDLINES
Narayana Swamy
 
Files io
Files ioFiles io
Files io
Narayana Swamy
 
Exceptions
ExceptionsExceptions
Exceptions
Narayana Swamy
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
Narayana Swamy
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
Narayana Swamy
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Exceptions
ExceptionsExceptions
Exceptions
Narayana Swamy
 

More from Narayana Swamy (7)

AICTE GUIDLINES AICTE GUIDLINESAICTE GUIDLINES
AICTE GUIDLINES  AICTE GUIDLINESAICTE GUIDLINESAICTE GUIDLINES  AICTE GUIDLINESAICTE GUIDLINES
AICTE GUIDLINES AICTE GUIDLINESAICTE GUIDLINES
 
Files io
Files ioFiles io
Files io
 
Exceptions
ExceptionsExceptions
Exceptions
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exceptions
ExceptionsExceptions
Exceptions
 

Recently uploaded

22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
ijaia
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
AjmalKhan50578
 
morris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdfmorris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdf
ycwu0509
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
Paris Salesforce Developer Group
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
Prakhyath Rai
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 

Recently uploaded (20)

22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
 
morris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdfmorris_worm_intro_and_source_code_analysis_.pdf
morris_worm_intro_and_source_code_analysis_.pdf
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 

Oop inheritance chapter 3

  • 2. What Is Inheritance? In the real world: we inherit traits from our motheran d father . We als o inherit traits from We our migh t grandmothe r, grandfathe r, an d ancestor s.have similar eyes, the same smile,A different height. But we are in many ways "derived" from our parents. In software: object inheritance is more well defined! Objects that are derived from other both object "resemble"their parent s by inheritin g stat e (fields ) an dbehavior (methods). 2 uu )
  • 3. Contd .Inheritanc e is A fundament al featur e of object- orientedprogrammin g whic h enable s the programmer to write A class based on an already existing class. Th e already existin g clas s is calle d the paren t clas s, or orsuperclas s, and the ne w clas s is calle d the subclas s,derived class. Th e subclass inherits (reuse s) the no n private member s(methods and variables) of the its own members as well. superclass, and may define Inheritance extends.  When class b is a subcla uss o uf class a, we say b is implemented in java usin g the keywor d 3 )
  • 4. Advantages Of Inheritance.Cod e reusabilit y:- inheritan ce automates the process of reusing the code of the superclasses in the subclasses.  With inheritance, an object can inherit its more general properties from its paren t object , and that save s th e redundanc y in programmin g. Cod e maintenan ce:- organizin g cod e int o hierarchic alclasses makes its maintenance and management easier. Implement ing OOP:- inheritance help s to impleme nt th ebasic 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. 4 uu )
  • 5. Inheritance TypesA. Single level inheritance:- inheritance in super class. which a class inherits from only one B. Multi- level inheritance: - inheritanc e in which a class inherits from a class which itself inherits from another class.Here a minimum of three classes is required. here two or more  C. Hierarchy inheritance:- inherits from one class. D. Multiple inheritance:- a more classes. classe s class inherits from two or This type of inheritance is not supported in java.  5 )
  • 6. Dog Class public class Dog { private String name;private int fleas; public Dog(string n, int f) { name = fleas = n; f; } public public public String getName() { return name; } int getFleas() { return fleas; } void speak() { System.out.println("woof"); } } 6 uu )
  • 7. CAT CLASSpublic class Cat { private string name; private int hairBalls; public Cat(string n, int name = n; hairballs = h; } h) { public public public String getName() { return name; } int getHairBalls() { return void speak() { hairballs; } System.out.println("meow"); } } 7 uu )
  • 8. Problem: Code Duplication Dog and Cat have the name field and the getName method in common Classes often in common have a lot of state and behavio r Resul t: lot s of duplicate code! 8 uu )
  • 9. Solution: Inheritance Inheritance allows you to write new classes that inherit from existing classes The existing class whose properties are inherited is called the "parent" or superclassThe new class that inherits the "child" or subclass Result: lots of code reuse! from the supe r clas s is calle d 9 uu )
  • 10. using inheritance superclass subclass subclass 10 ) Dog int fleas int getFleas() void speak() uu Cat int hairballs int getHairballs() voidspeak() Animal String name String getName() Cat String name int hairballs String getName() int getHairballs() voidspeak() Dog String name int fleas String getName() int getFleas() void speak()
  • 11. Animal Superclass public { class Animal private String name; public Animal(string n) { name = n; } public String getName() { return name; } } 11 uu )
  • 12. Dog Subclass public class Dog extends Animal { private int fleas; public Dog(string n, int f) { super(n); // calls animal fleas = f; constructor } public int getFleas() return fleas; } { public void speak() { return System.out.println("woof"); } uu } 12 )
  • 13. Cat Subclass public class Cat extends Animal { private int hairballs; public Cat(string n, int h) { super(n); // calls animal hairballs = h; constructor } public int getHairBalls() { return hairballs; } public void speak() { return System.out.println("meow"); } } 13 uu )
  • 14. Inheritance Quiz 1 • What is the output of the following?Dog d Cat c = = new Dog("rover" 3); new Cat("kitty", 2); System.out.println(d.getName() + " has " + d.getFleas() + " fleas"); System.out.println(c.getName() + " has " + c.getHairBalls() + " hairballs"); rover has 3 fleas kitty has 2 hairballs 14 (Dog and Cat inherit the ge utN uame method from )
  • 15. Inheritance Rules Us e the extends keyword to indicat e that one clas sinherits from another The subclass inherits all the nonprivate fields and methods of the superclass Use the super keyword in the subclas s constructor to cal lthe superclas s constructor 15 uu )
  • 16. Subclass Constructor • The first thing a subclass constructor must do is call the superclass constructor. • This ensures that the superclass part of the object is constructed before the subclass part • If you do not call the superclass constructor with the super keyword, and the superclass has a constructor with no arguments, then that superclass 16 uu )
  • 17. Implicit Supe r Constructor Call then this Beef subclass: public class Beef extends Food private double weight; public Beef(double w) { weight = w } } { if I have this food class: public class food { private boolean public food() { raw = true; } } raw; is equivalent to: public class Beef extends Food private double weight; public Beef(double w) { super(); weight = w { 17 } u}u )
  • 18. Inheritance Quiz 2public class public A() } A { { System.out.println("I'm A"); } public class public B() } B { extends A { System.out.println("I'm B"); } public class public C() } C { extends B { System.out.println("I'm C"); } What does this print out? I'm I'm I'm A B CC x = new C(); 18 uu )
  • 19. Overriding Methods When a method type signature as method is said to in a super class has the same name as and a method in the superclass, then the subclass override the method in the superclass.  During overriding a method the following takes place:  The new method overrides (and hides) the original method.  When you override a method, you can call the superclass's copy of the method by using the syntax super.method().  You can not do super.super. to back up two levels.  You canno t chang e the return type whe n overridin g impossibl e. a method, since this would make polymorphism uu )
  • 20. class MyDerived extends { int y; MyBase class MyBase { private int public MyDerived(int { super(x); } public MyDerived(int { super(x); x) x; public MyBase(int { x) x, int y) this.x } = x; public { return } public { int getX() this.y } public { return } public { = y; x; int getY() void show() y; System.out.println("x=" } } + x); void show() super.show(); System.out.println("y = " + y); } 20 uu} )
  • 21. Final Variables, Methods And Class es All methods and variables in subclasses. can be overridden by default  Use th e fin al keywor d member s to of preven t th e subclass es from overriding the Example: final th e superclas s. This method will not be overridden int num=10; public final void show() { System.out.println("x=" + } x);  It is also possible to define a class as final if we class not to be inherited.  Any attempt to inherit a final class will cause wan t th e an error 21 )
  • 22. Abstract Classes An abstract method is a method that is declared without implementation . an Exampl e: abstract void display(); An abstrac t clas s is a clas s that is incomplet e, or to be considered incomplete. Only abstract classes may have abstract methods, that is ,  methods that are declared but not yet implemented and non abstract methods. An abstract class may or may not contain abstract methods. An abstract class is a class that cannot be instantiated, we   cannot create instances of uan uabstract 22 )
  • 23. Contd. While using abstract classes:  We cannot use abstract classes directly. to instantiate objects  The abstract method of an abstract clas s mus t be defined in its subclass.  We cannot declare abstract constructors or abstrac tstatic methods.  Abstract classes can methods and one or have none, one or more abstrac tmore non abstract methods. 23 )
  • 24. abstract class A { abstract void callme(); // abstract method void callmetoo() // Non-abstract method { System.out.println("This is a concrete method."); } } class B extends A { void callme() //Implementation of super class’s { abstract method System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { A A B ab;// possible ab1=new A(); b = new B(); // Is not correct b.callme(); b.callmetoo(); 24 uu} } )
  • 25. Visibility Control (Access Level)  By using inheritance it is possible to inherit all members of the superclass being on the subclasses.  But it is also possible to restrict from outside the class. This s done the access of certain fields using access modifiers.  Classes can contain fields and method s of four different access levels: A. private:- private variable s and method s are accessibl ewithin their own class (access only to the class itself) . B. Friendly access:- when no access modifier is specified, themembers’ are access only to classes in the same No access level is specified in this case. package . 25 )
  • 26. Contd. C. protected:- makes the fields visible to all classes andsubclasses within th e sam e package and to all subclasses from other packages. D. Private protecte d:- make s th e fields visible in all subclasses regardless of what package they are in. These fields are not accessible by other classes in the same package. E. public:- These variables or methods have access to all classes everywhere. 26 such members. u ))
  • 27. Programming Example A company has a list of employees. It asks you to provide a payroll sheet for all employees. Has extensive data (name, department, pay employees. amount, …) for all Different types engineer. You have an old employee class but need to of employee s – manager , enginee r, softwar e add very different data and methods for managers and engineers. Suppose someone wrote a nam e syste m, and already provided a legacy employee class.  The old employee class had a printData() method for eachemployee that only printed the name. We want to reuse it, and 27 uuprint pay info. )
  • 28. Review PictureMessage passing "Main event loop"Encapsulation Employee e1 private: lastName firstName uu ) printData public … Main(…){ Employee e1…("Mary","Wang"); ... e1.printData(); // Prints Employee names. ... } 28
  • 29. Employee class //This is a simpler super class class Employee { // Data private String firstName, lastName; // Constructor public Employee(String fName, String lName) { firstName= fName; lastName= lName; } // Method public void printData() { System.out.println(firstName + " " + lastName);} } 29 uu )
  • 30. Inheritance Diagram Already written: Class Employee printData()firstName lastName is-a Class Engineer is-a Class Manager firstName lastName firstName lastName hoursWorked salary wagesprintData() getPay() printData() getPay() 30 You une uxt write: )
  • 31. Engineer Class //A subclass derived from Employee class class Engineer extends Employee { private double wage; private double hoursWorked; public Engineer(String fName, String lName, double rate, double super(fName, lName); wage = rate; hoursWorked = hours; hours) { } public double getPay() { return wage * hoursWorked; } public void printData() { super.printData(); System.out.println("Weekly uu // PRINT NAME pay: Birr" + getPay(); 31 } } )
  • 32. Manager Class //A subclass derived from Employee class class Manager extends Employee { private double salary; public Manager(String fName, super(fName, lName); salary = sal; } String lName, double sal){ public double getPay() { return salary; } public void printData() { super.printData(); System.out.println("Monthly salary: Birr" + salary);} } 32 uu )
  • 34. Sales Manager Class //A subclass derived from Manager class class SalesManager extends Manager { private double salesBonus; commission. // Bonus Possible as // A SalesManager gets a constant public SalesManager(String fName, super(fName, lName, 1250.0); salesBonus = b; } salary String of $1250.0 lName, double b) { public double getPay() { return 1250.0; } public void printData() { super.printData(); System.out.println("Bonus Pay: uu $" + salesBonus; } 34 } )
  • 35. Main Method public class PayRoll { public static void main(String[] args) { // Object creation and Initialization (Using constructors) Engineer fred Manager ann = new Engineer("Fred", "Smith", 12.0, 8.0); = new Manager("Ann", "Brown", 1500.0); SalesManager mary= new SalesManager("Mary", "Kate", 2000.0); // Polymorphism, or late binding Employee[] employees = new Employee[3]; employees[0]= employees[1]= employees[2]= fred; ann; mary; System.out.println(“===========================“); for (int i=0; i < 3; i++) employees[i].printData(); System.out.println(“===========================“); } uu 35 } )
  • 36. Output from Main =========================== Fred Smith Weekly pay: $96.0 Ann Brown Monthly salary: $1500.0 Mary Barrett Monthly salary: $1250.0 Bonus: $2000.0 =========================== Note that we could not write: employees[i].getPay(); Method becaus e getPay( ) is no t a metho d of th e supercla ssEmployee. In contrast, printData() is a method of can find the appropriate version. Employee, so Java 36 )
  • 37. Object Class All java classes implicitly inherit from java.lang.Object So every class you write will automatically have methods in object such as equals, and toString etc. We'll learn about the importanc e of som e of thes e methods inlater lectures . 37 uu )