Академический Документы
Профессиональный Документы
Культура Документы
Inheritance
u
1
0
What Is Inheritance?
In the real world: we inherit traits from our mother
and father. We also inherit traits from our
grandmother, grandfather, and ancestors. We might
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 object "resemble"
their parents by inheriting both state (fields) and
behavior (methods).
2
uu )
Contd.
Inheritance is A fundamental feature of object-oriented
programming which enables the programmer to write A
class based on an already existing class.
The already existing class is called the parent class, or
superclass, and the new class is called the subclass, or
derived class.
The subclass inherits (reuses) the non private members
(methods and variables) of the superclass, and may define
its own members as well.
Inheritance is implemented in java using the keyword
extends.
3
When class b is a subcla ss o f class a, we say b extends
uu )
Advantages Of Inheritance.
Code reusability:- inheritance 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
uu )
Inheritance Types
A. Single level inheritance:- inheritance in which a
class inherits from only one super class.
B. Multi-level inheritance:- inheritance in which a
class inherits from a class which itself inherits from
another class.
Here a minimum of three classes is required.
C. Hierarchy inheritance:- here two or more classes
inherits from one class.
D. Multiple inheritance:- a class inherits from two or
more classes.
This type of inheritance is not supported in java.
5
uu )
Dog Class
public class Dog {
private String name;
private int fleas;
public Dog(string n, int f) {
name = n;
fleas = f;
}
public String getName() { return name; }
public int getFleas() { return fleas; }
public void speak() {
System.out.println("woof");
}
} 6
uu )
CAT CLASS
public class Cat {
private string name;
private int hairBalls;
uu )
Problem: Code Duplication
uu )
Solution: Inheritance
uu )
Dog String Cat String
name int name int
fleas hairballs
String getName() String getName()
int getFleas() int getHairballs()
void speak() voidspeak()
using
inheritance
superclass
Animal String
subclass
name String
subclass getName()
Dog Cat
int fleas int int hairballs int
10
getFleas()
void speak() uu getHairballs()
voidspeak() )
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 {
uu )
Cat Subclass
public class Cat extends Animal {
uu )
Inheritance Quiz 1
14
(Dog and Cat inherit the getName method from Animal)
uu )
Inheritance Rules
Use the extends keyword to indicate that one class
inherits from another
The subclass inherits all the nonprivate fields and methods
of the superclass
Use the super keyword in the subclass constructor to call
the superclass 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
constructor will be called implicitly.
16
uu )
Implicit Super Constructor Call
then this Beef subclass:
uu )
Overriding Methods
When a method in a super class has the same name as and
type signature as a method in the superclass, then the subclass
method is said to override the method in the superclass.
During overriding a method the following takes place:
uu )
class MyDerived extends MyBase
{
int y;
class MyBase
public MyDerived(int x)
{
{
private int x;
super(x);
public MyBase(int x)
}
{
public MyDerived(int x, int y)
this.x = x;
{
}
super(x);
public int getX()
this.y = y;
{
}
return x;
public int getY()
}
{
public void show()
return y;
{
}
System.out.println("x=" + x);
public void show()
} {
}
super.show();
System.out.println("y = " + y);
} 20
uu }
)
Final Variables, Methods And Classes
All methods and variables can be overridden by default
in subclasses.
Use the final keyword to prevent the subclasses from
overriding the members of the superclass.
Example: final int num=10; This method
will not be
public final void show()
overridden
{
System.out.println("x=" + x);
}
uu
and the compiler will not allow it.
)
Abstract Classes
An abstract method is a method that is declared without an
implementation .
Example: abstract void display();
An abstract class is a class that is incomplete, 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.
uu )
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 ab;// possible
A ab1=new A(); // Is not correct
B b = new B();
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 the access of certain fields
from outside the class. This s done using access modifiers.
Classes can contain fields and methods of four different
access levels:
A. private:- private variables and methods are accessible
within their own class (access only to the class itself).
B. Friendly access:- when no access modifier is specified, the
members’ are access only to classes in the same package.
No access level is specified in this case. 25
u
) )
Contd.
C. protected:- makes the fields visible to all classes and
subclasses within the same package and to all
subclasses from other packages.
D. Private protected:- makes the 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.
Even classes from any package can have access to 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 amount, …) for all
employees.
Different types of employees – manager, engineer, software
engineer.
You have an old employee class but need to add very different
data and methods for managers and engineers.
Suppose someone wrote a name system, and already
provided a legacy employee class.
The old employee class had a printData() method for each
employee that only printed the name. We want to reuse it, and
27
public … Main(…){
Employee e1
printData Employee e1…("Mary","Wang");
...
private: e1.printData();
lastName
firstName // Prints Employee names.
...
}
28
uu )
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
firstName printData()
lastName
is-a is-a
Class Engineer
Class Manager
firstName firstName
lastName lastName
hoursWorked
salary
printData() wages
getPay()
printData()
getPay()
30
uu
You ne xt 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 hours) {
super(fName, lName);
wage = rate;
hoursWorked = hours;
}
public double getPay() {
return wage * hoursWorked;
}
public void printData() {
super.printData(); // PRINT NAME
System.out.println("Weekly pay: Birr" + getPay();
} 31
}
uu )
Manager Class
//A subclass derived from Employee class
class Manager extends Employee {
private double salary;
uu )
Inheritance…
Class Manager
firstName
lastName
is-a
printData Salary
getPay
Class SalesManager
firstName
lastName
printData Salary
getPay 33
salesBonus
uu )
Sales Manager Class
//A subclass derived from Manager class
class SalesManager extends Manager {
private double salesBonus; // Bonus Possible as
commission.
37
uu )