Chapter6 Inheritance
Chapter6 Inheritance
INHERITANCE
3
Inheritance
1. What is Inheritance?
2. Why Inheritance?
3. How to use it?
4. Superclass & Subclass
1. WHAT IS
INHERITANCE?
5
}
2. Then create a test class, say, TestBlank
public class TestBlank {
public static void main(String[] args){
BlankSample bs = new BlankSample();
System.out.print(bs.toString());
}
}
The question is why we can call bs.toString()?
If we look at BlankSample, there is toString(). Why?
9
2. WHY INHERITANCE?
12
2. Why Inheritance?
• Classes often share capabilities
• We want to avoid re-coding these capabilities
• Reuse of these would be best to
• Improve maintainability
• Reduce cost
• Improve “real world” modeling
13
public Circle(){}
public Circle(double radius){
this.radius = radius;
}
public void setRadius(double radius){
this.radius = radius;
}
public double findArea(){
return radius * radius *3.14;
}
}
16
4. SUPERCLASS &
SUBCLASS
21
Circle Cylinder
5. USING KEYWORD
SUPER
26
super():
1. MUST be written in the 1st line of subclass constructors
2. Cannot be written in other methods
3.Is the only way to call superclass constructor.
28
Note:
• This keyword is not always used to call methods from superclass.
• We can call superclass methods by calling directly the methods
name. Please look at slide # 14.
• However, super is used not to confuse with the name of the
overriding methods.
29
6. OVERRIDING
METHODS
30
1 error
37