Java_OOPS1
Java_OOPS1
# Encapsulation
• Encapsulation is “Wrapping of data in a single unit, with
hiding the data from another classes.”
• Fully Encapsulated class properties
a) All the attributes, data members must be declared
private.
b) There must be methods i.e. member functions
declared public to be used in other classes.
c) The class must have the getter and setter methods,
If the data members are required to access or modify
in another classes.
• Example of Encapsulation:
These are the example files where we do Encapsulation
of data in Student.java class.
class Student {
// data members i.e. attributes declared
private
private int rollNo;
private String firstName;
private String lastName;
b) By using Interface.
• By using Interface, we can achieve 100% Abstraction of
data.
• In Interface we cannot declare the methods as non-
abstract methods.
• Any method or implementation inside the Interface is
always abstract whether you use abstract keyword or
not.
• The object of the Interface is not created directly, it is
not instantiated directly.
• Instead, we create a sub class that implements the
interface and its abstract methods.
• We create the object of the Interface using the sub
class.
• Types of inheritance
a) Single level inheritance:
Example:
class Student {
void study() {
System.out.println("Student is studying.");
}
}
interface Athletic {
void playSports();
}
@Override
public void playSports() {
System.out.println("High school student is playing sports.");
}
}
interface Athletic {
void playSports();
}
class CollegeStudent extends Student {
void attendClass() {
System.out.println("College student is attending class.");
}
}
class HighSchoolStudent extends Student implements Athletic {
@Override
public void playSports() {
System.out.println("High school student is playing sports.");
}
}
public class Main {
public static void main(String[] args) {
CollegeStudent cs = new CollegeStudent();
cs.study(); // Output: Student is studying.
cs.attendClass(); // Output: College student is attending class.
A) Compile-time polymorphism:
1) Limitations of OOPs
- Complexity of code increases.
- Code length increases.