L06 - Encapsulation and Inheritance
L06 - Encapsulation and Inheritance
Inheritance
IT 213 – Object Oriented Programming
Overview
• Overloading • super Keyword
Methods
• Overriding Methods
• Encapsulation
• protected Access
• Inheritance Modifier
• Super Class and Sub • UML Class Diagram
Classes Notation
• extends Keyword
Overloading Methods
• Method overloading
− When methods have the same name, but different
parameters
− When you need the same method functionality for
different types of parameters.
• Overloaded methods have the following properties:
− the same name
− different parameters
− return types can be different or the same
Overloading Methods
1. public void add(int x, int y, int z){
2. int sum = x + y + z;
3. System.out.println(sum);
4. }
5.
6. public void add(double x, double y){
7. double sum = x + y;
8. System.out.println(sum);
9. }
Encapsulation & Inheritance
• Encapsulation
− Means that data and instructions are wrapped up
together and treated as a unit
• Inheritance
− Ability to “inherit”, use or modify existing or
predefined classes
Encapsulation
• The idea behind encapsulation is to ensure that
implementation details are not visible to users. The
variables of one class will be hidden from the other
classes, accessible only through the methods of the
current class.
• To achieve encapsulation in Java, declare the class'
variables as private and provide public setter and getter
methods to modify and view the variables' values.
Encapsulation
• For example:
1.public class BankAccount {
2. private double balance=0;
3. public void deposit(double x) {
4. if(x > 0) {
5. balance += x;
6. }
7. }
8.}
SubClass SubClass
Class Diagram: Inheritance
Employee
+id: int
+name: String
+displayType(): void
Instructor Secretary