Lecture 3 - Object Oriented Programming Concepts
Lecture 3 - Object Oriented Programming Concepts
OOP Concepts
2. Inheritance
3. Abstraction
4. Polymorphism
1. Encapsulation
Encapsulation
• Encapsulation hides the implementation details
-> Data shielding
Encapsulation Benefits
• Ensures that structural changes remain local:
• Changing the class internals does not affect any code outside
of the class
• Encapsulation allows adding some logic when accessing
client's data
• E.g. validation on modifying a property value
• Hiding implementation details reduces complexity ->
easier maintenance
• Fields can be made read-only or write-only
Modifiers
Access Modifiers Non-Access Modifiers
public final
protected abstract
default static
private strictfp
synchronize
native
transit
Volatile
Access Modifiers
• Specifies the accessibility or scope of a field, method,
constructor, or class.
• We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
Access Subclass
Class Package Global
Modifiers Same Package Different Package
class B{
public static void main(String args[]){
A obj = new A();
//trying to access private method of
another class
obj.display();
}
}
public class A{
protected void display(){
System.out.println("Inside display method");
}
}
package p2;
import p1.*; //importing all classes in package p1
//Class B is subclass of A
class B extends A{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
} Inside display method
Example 4
package p1;
public class A{
public void display(){
System.out.println("Inside display method");
}
}
package p2;
import p1.*;
class B{
public static void main(String args[]){
A obj = new A;
obj.display();
}
}
}
}
Types of Inheritance