Java Course
OOP(Object Oriented Programming)
It is a programming technique based on the concept of Class and Object.
Class
A class is a template which describe about data and behavior of an object. In below example, Class CricketScorer is the template for creating multiple objects.
Let's look at an example:
public class CricketScorer { // Instance Variables - constitute the state of an object private int score; // Behavior - all the methods that are part of the class // An object of this type has behavior based on the // methods four, six and getScore public void four() { score = score + 4; } public void six() { score = score + 6; } public int getScore() { return score; } public static void main(String[] args) { CricketScorer scorer = new CricketScorer(); scorer.six(); // State of scorer is (score => 6) scorer.four(); // State of scorer is (score => 10) System.out.println(scorer.getScore()); } }
Object
An object is an instance of class which can be related to real life example with its attributes(data) and methods(behavior).
In the above example, we create an object using new CricketScorer(). The reference of the created object is stored in scorer variable. We can create multiple objects of the same class.
What is state of an Object?
Values assigned to instance variables of an object. Consider following code snippets from the above example. The value in score variable is initially 0. It changes to 6 and then 10. State of an object might change with time.
scorer.six(); //State of scorer is (score => 6) scorer.four(); //State of scorer is (score => 10)
What is behavior of an Object?
Methods supported by an object. Above example the behavior supported is six(), four() and getScore().
What is the super class of every class in Java?
Every class in java is a sub class of the class Object. When we create a class we inherit all the methods and properties of Object class.
Let's look at a simple example:
System.out.println(str.toString()); System.out.println(str.hashCode()); if(str instanceof Object){ System.out.println("I extend Object");//Will be printed }
toString and hashCode methods for String class are inherited from Object class and overridden. (Note: clone() is also inherited from Object, but String does not override it and does not implement Cloneable, so calling str.clone() directly would result in a compile-time error since clone() is protected in Object.)
Core OOP concepts are:
- Encapsulation
- Abstraction
- Polymorphism
- Inheritance
- Association
- Aggregation
- Composition
- Coupling
- Cohesion
1. Encapsulation
Encapsulation or data binding is about packaging of data(variable) and behavior(method) together in a class.
- Declare the variables of a class as private
- Provide public setter and getter methods to modify and view the variable values.
- The constructor can be used to initialize the object when it's created, setting the initial state of the object. It's a method that helps set up the object with necessary data at the time of instantiation.
Sample code
class CheckingAccount { // Step 1: Declare the balance variable as private (data hiding) private double balance; // Step 2: Constructor - Used to initialize the object when created public CheckingAccount(double initialBalance) { balance = initialBalance; // Initialize balance during object creation } // Step 3: Setter - Provides controlled access to modify the balance public void setBalance(double bal) { if (bal >= 0) { // Ensures balance can't be set to a negative value balance = bal; } else { System.out.println("Balance cannot be negative."); } } // Step 4: Getter - Provides controlled access to retrieve the balance public double getBalance() { return balance; } }
2. Abstraction
It is a process of hiding the implementation details from the user, only functionality will be provided to the user. This can be achieved by Abstract class and Interface.
Interface
It is an abstract type that is used to specify a behaviour that class must implement
- By default the variables in an interface are public final static.
- By default the methods are public abstract but in Java 8 default, static concrete methods are also introduced.
- In Java 8, interface having one abstract method is denoted by annotation @FunctionalInterface.
- Interface can extend one or more interface.
- Interface can be nested inside another interface.
interface Employee{ double calculateSalary(); void displayInfo(); }
Abstract class
- An abstract class is a class with both abstract and concrete methods.
- An abstract class cannot be instantiated but they can be sub-classed.
- An abstract class can support non-static, non-final methods and attributes(protected, private in addition to public)
- An abstract class can hold state of the object.
- It can have constructor and member variables where as interface default methods cannot hold state and it cannot have constructor and member variables as well.
Sample code
Employee
abstract class Employee { private int id; private String name; private String email; public Employee(int id, String name, String email) { this.id = id; this.name = name; this.email = email; } // Getter and Setter methods public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } // Abstract method to calculate salary public abstract double calculateSalary(); // Display employee info public void displayInfo() { System.out.println("Employee ID: " + id); System.out.println("Employee Name: " + name); System.out.println("Employee Email: " + email); } }

3. Polymorphism
It is a concept by which we can perform a single action by different ways.
- Overriding(dynamic/runtime)
- Overloading(static/compile time)
Method Overriding
Rules:
- Defining multiple methods with same name,same parameters and same return type(or co-variant return type) in super class and sub class known as method overriding.
- We cannot override a private method of super class in sub class as private methods are not accessible in sub class.
- We cannot override a static method of super class in sub class as static means class level.
- We can change accessibility modifier in sub class overridden method but should increase the accessibility if we decrease compiler will throw an error message.
For Exceptions
- If sub class throws checked exception super class should throw same or super class exception of this.
- If Super class method throws an exception, then Subclass overriden method can throw the same exception or no exception, but must not throw parent exception of the exception thrown by Super class method.
It means, if Super class method throws object of NullPointerException class, then Subclass method can either throw same exception, or can throw no exception, but it can never throw object of Exception class (parent of NullPointerException class).
Sample code
FullTimeEmployee
// FullTimeEmployee Class (Inherits Employee) class FullTimeEmployee extends Employee { private double baseSalary; public FullTimeEmployee(int id, String name, String email, double baseSalary) { super(id, name, email); this.baseSalary = baseSalary; } // Implement the calculateSalary method for full-time employee public double calculateSalary() { return baseSalary; } // Overload displayInfo to include salary @Override public void displayInfo() { super.displayInfo(); System.out.println("Salary: $" + calculateSalary()); } }
PartTimeEmployee
// PartTimeEmployee Class (Inherits Employee) class PartTimeEmployee extends Employee { private double hourlyRate; private double hoursWorked; public PartTimeEmployee(int id, String name, String email, double hourlyRate, double hoursWorked) { super(id, name, email); this.hourlyRate = hourlyRate; this.hoursWorked = hoursWorked; } // Implement the calculateSalary method for part-time employee public double calculateSalary() { return hourlyRate * hoursWorked; } // Overload displayInfo to include salary @Override public void displayInfo() { super.displayInfo(); System.out.println("Hourly Rate: $" + hourlyRate); System.out.println("Hours Worked: " + hoursWorked); System.out.println("Salary: $" + calculateSalary()); } }
EmployeeManager
// EmployeeManager Class class EmployeeManager { // Methods to manage employees public void printEmployeeInfo(Employee employee) { employee.displayInfo(); } public void printSalary(Employee employee) { System.out.println("Salary: $" + employee.calculateSalary()); } }
EmployeeManagementSystem
// Main Class to Demonstrate the System public class EmployeeManagementSystem { public static void main(String[] args) { // Create instances of FullTimeEmployee and PartTimeEmployee FullTimeEmployee fullTimeEmployee = new FullTimeEmployee(1, "Praveen Oruganti", "praveen.oruganti@syf.com", 5000); PartTimeEmployee partTimeEmployee = new PartTimeEmployee(2, "Ravi Kanala", "ravi.kanala@hcltech.com", 20, 80); // Create an EmployeeManager instance EmployeeManager manager = new EmployeeManager(); // Display information for full-time employee System.out.println("Full-Time Employee Information:"); manager.printEmployeeInfo(fullTimeEmployee); // Display information for part-time employee System.out.println("\nPart-Time Employee Information:"); manager.printEmployeeInfo(partTimeEmployee); // Calculate and display the salary for both employees System.out.println("\nFull-Time Employee Salary:"); manager.printSalary(fullTimeEmployee); System.out.println("\nPart-Time Employee Salary:"); manager.printSalary(partTimeEmployee); } }
Output
Full-Time Employee Information: Employee ID: 1 Employee Name: Praveen Oruganti Employee Email: praveen.oruganti@syf.com Salary: $5000.0 Part-Time Employee Information: Employee ID: 2 Employee Name: Ravi Kanala Employee Email: ravi.kanala@hcltech.com Hourly Rate: $20.0 Hours Worked: 80.0 Salary: $1600.0 Full-Time Employee Salary: Salary: $5000.0 Part-Time Employee Salary: Salary: $1600.0
Method Overloading
If a class has multiple methods having same name but different in parameters is known as Method Overloading. There are 2 types to overload a method
- by changing number of arguments
- by changing the datatype
Method overloading is not possible by changing the return type of method only.
One type is promoted to another implicitly if no matching datatype is found.
There will be ambiguity in some cases when there are no matching type arguments, each method promotes similar number of arguments.
For example
void sum(int a, long b) { System.out.println("a"); } void sum(long a, long b) { System.out.println("b"); } obj.sum(20, 20) ; // NOT ambiguous - resolves to sum(int, long) and prints "a" // sum(int, long) is more specific than sum(long, long), since any argument // valid for sum(int, long) can also be widened to fit sum(long, long), but not vice versa.
A genuinely ambiguous case would need neither overload to dominate the other, for example:
void sum(int a, long b) { System.out.println("a"); } void sum(long a, int b) { System.out.println("b"); } obj.sum(20, 20) ; // ambiguity // compile time error
One type is not depromoted implicitly for example double cannot be depromoted to any type implicitly.
Thrown exceptions from methods are not considered.
Normally we are developing our application interface base approach for example service and serviceImpl so my controller need to inject serviceImpl to get business functionality so in this case in controller class we are injection service bean by taking service interface reference as below.
public interface BankService { public void doTransaction(); } @Service public class BankServiceImpl implements BankService{ @Override public void doTransaction() { // LOGIC } } @Controller public class BankController { @Autowired(required = true) private BankService service; }
Here internally IOC container instantiate my service bean as below approach
BankService service=new BankServiceImpl();//Runtime polymorphism
4.Inheritance(IS-A relationship)
A subclass can inherit the states and behaviors of it super class is known as Inheritance.
Multiple inheritance is not possible due to ambiguity problem and cyclic inheritance is not allowed on Java.
5.Association(HAS-A relationship)
Association is a relationship between two classes where one class utilizes feature of another class. It is HAS-A relationship.
For example
-
Student and ContactInfo.
All Student HAS A ContactInfo.
-
Student and StudentIdCard.
All Student HAS A StudentIdCard.
6. Aggregation
It is a type of association where it is HAS-A relationship and existence of both the class are not dependent on each other.
Let's see an example
public class Team { private final List<Member> members; public Team(List<Member> members) { this.members = members; } } class Member { private final String name; Member(String name) { this.name = name; } }
Here in this example, members are not destroyed when Team object is destroyed.
Other good examples could be
- Pond object (aggregate object) and Duck objects (component parts), where ducks may come for sometime in the pond for swimming.
- a department has several professors.
- Student has a ContactInfo. They are dependent on each other as ContactInfo can be used anywhere else for example Employee class.
7. Composition
It is a type of association where it is HAS-A relationship. In this relationship ClassB cannot exists without Class A whereas Class A can exist without ClassB.
Let's see an example,
public class Organization { private final List<Department> departments; public Organization() { departments = new ArrayList<>(); departments.add(new Department("Finance")); departments.add(new Department("HR")); departments.add(new Department("Technical")); } } class Department { private final String name; Department(String name) { this.name = name; } }
Composition is implemented using component part object Initialization inside constructor (or sometimes post construction). All the component parts are destroyed as soon as composite object is destroyed.
Other good examples could be
- LinkedList composite object consisting of Nodes (component parts)
- A university has several departments.
8. Coupling
Coupling indicates level of dependency between two classes.
In good software design, classes should be loosely coupled to each other for example Spring Framework.
9.Cohesion
Cohesion indicates level of logical connection of methods and attributes used in a class.
In good software design,Classes should be highly Cohesive.