Java OOPs Concepts Made Simple: A Complete Beginner-Friendly Guide (Part-3)
OOPS in Java – Coupling, Cohesion & Interface (Complete Guide with Examples & Interview Questions)
Master Coupling, Cohesion, Interfaces, Marker Interfaces, Adapter Classes, and Interview Questions in Java.
- Coupling vs Cohesion
- Loose Coupling & High Cohesion
- Interface in Java
- extends vs implements
- Interface Methods & Variables
- Marker Interface
- Adapter Classes
- Interface vs Abstract Class
- Constructor Interview Questions
Coupling vs Cohesion Explained
Writing software isn't just about making code work today. The real goal is to build code that is easy to modify, debug, and expand tomorrow.
Two of the most important design principles every Java developer should understand are:
- Coupling
- Cohesion
1. Coupling – How Connected is Your Code?
Coupling refers to the degree of dependency between different classes or components.
| Type | Meaning |
|---|---|
| Tight Coupling | Classes heavily depend on each other. |
| Loose Coupling | Classes interact through simple, independent connections. |
Real-Life Analogy
Imagine two different computer mice:
- Built-in wired mouse: If it breaks, repairing it affects the entire laptop. This is Tight Coupling.
- Bluetooth mouse: If it breaks, simply replace it. The laptop keeps working normally. This is Loose Coupling.
Java Example: Tight Coupling
class A {
static int x = B.j;
}
class B {
static int j = C.x;
}
class C {
static int x = Main.m1();
}
class Main {
public static int m1() {
return 10;
}
public static void main(String[] args) {
System.out.println("Start small. Ship something.");
}
}
Why is this Tight Coupling?
Notice the dependency chain:
- Class A depends on B
- Class B depends on C
- Class C depends on Main
A small change in one class can unexpectedly affect every other class.
- Hard to enhance
- Difficult debugging
- Poor maintainability
- Low reusability
- High risk of breaking existing code
Golden Rule
2. Cohesion – How Focused is Your Code?
Cohesion measures how closely related the responsibilities inside a class are.
| Type | Meaning |
|---|---|
| Low Cohesion | One class performs many unrelated tasks. |
| High Cohesion | One class performs one clear responsibility. |
Real-Life Analogy
- Swiss Army Knife → Many tools, none perfect → Low Cohesion.
- Dedicated Screwdriver → One job, done perfectly → High Cohesion.
Benefits of High Cohesion
- Easier maintenance
- Better readability
- Higher reusability
- Safer modifications
- Cleaner architecture
Coupling vs Cohesion
| Feature | Coupling | Cohesion |
|---|---|---|
| Measures | Dependency | Focus |
| Ideal | Loose | High |
| Benefits | Flexibility | Maintainability |
Remember This Interview Line
Keep every class focused on a single responsibility while minimizing dependencies between classes. This simple principle makes software easier to maintain, test, and scale.
Interface in Java – Complete Guide
An Interface in Java can be considered as a Service Requirement Specification, a contract between a client and a service provider, or a 100% pure abstract class.
It defines what should be done, but not how it should be done. The implementation is provided by the classes that implement the interface.
A client defines the requirements, and multiple service providers can implement those requirements in their own way.
Real-Life Example: JDBC API
One of the best examples of interfaces is JDBC (Java Database Connectivity).
The JDBC API acts as a common specification for developing database drivers.
- Oracle provides the Oracle JDBC Driver.
- MySQL provides the MySQL JDBC Driver.
- PostgreSQL provides the PostgreSQL JDBC Driver.
Since every database vendor follows the same JDBC interface, Java applications can switch databases without changing their core code.
JDBC is one of the most common real-world examples used to explain why interfaces exist.
Implementing an Interface
Interfaces are implemented using the implements keyword.
Whenever a class implements an interface:
- Every interface method must be implemented.
- If all methods aren't implemented, the class must be declared as abstract.
- Since interface methods are automatically public, the implementation must also be public.
Example
interface Interf {
void m1();
void m2();
}
abstract class ServiceProvider implements Interf {
public void m1() {
System.out.println("m1 implemented");
}
}
class SubServiceProvider extends ServiceProvider {
public void m2() {
System.out.println("m2 implemented");
}
}
How This Works
- Interf declares two methods.
- ServiceProvider implements only one method.
- Since one method remains unimplemented, it becomes an abstract class.
- SubServiceProvider completes the remaining implementation.
extends vs implements
Many beginners confuse these two keywords. Here's the difference.
| Feature | extends | implements |
|---|---|---|
| Used with | Class inheritance | Interface implementation |
| Multiple inheritance | No | Yes |
| Keyword order | Comes first | Comes after extends |
A Class Can Extend Only One Class
class A extends B {
}
An Interface Can Extend Multiple Interfaces
interface A {
}
interface B {
}
interface C extends A, B {
}
A Class Can Implement Multiple Interfaces
class A implements C, D, E {
}
A Class Can Extend One Class and Implement Multiple Interfaces
class X extends Z implements Y {
}
Incorrect Syntax
class X implements Y extends Z {
}
This causes a compile-time error because extends must always come before implements.
Quick Quiz
Which statement is valid?
- A class can extend any number of classes.
- A class can implement only one interface.
- An interface can extend only one interface.
- An interface can implement multiple interfaces.
- A class can either extend a class or implement interfaces, but not both.
- None of the above.
Answer: 6) None of the above
Interface Methods
Every method inside an interface is automatically:
- public
- abstract
Even if you don't write these modifiers, Java adds them automatically.
Example
interface Interf {
void m1();
}
This is exactly equivalent to:
public abstract void m1();
Why?
- public → Every implementation class must access it.
- abstract → The implementation class provides the method body.
Modifiers Not Allowed
These modifiers cannot be used with abstract interface methods:
- private
- protected
- final
- synchronized
- strictfp
- native
Quiz: Which Declaration is Valid?
- public void m1() {}
- private void m1();
- protected void m1();
- static void m1();
- public abstract native void m1();
- abstract public void m1();
Answer: abstract public void m1();
Interface Variables
Interfaces can contain variables, but their primary purpose is to define constants.
Every interface variable is automatically:
- public
- static
- final
Example
interface Interf {
int x = 10;
void m2();
}
Java automatically treats it as:
public static final int x = 10;
Initialization is Mandatory
interface Interf {
int x;
}
This produces a compile-time error because interface variables must be initialized immediately.
Constants Cannot Be Modified
interface Interf {
int x = 10;
}
class Main implements Interf {
public static void main(String[] args) {
x = 777;
System.out.println(x);
}
}
Compile-time Error:
Interface Naming Conflicts
Sometimes multiple interfaces contain members with the same name.
Case 1: Same Method Signature
interface Left {
void m1();
}
interface Right {
void m1();
}
class Test implements Left, Right {
public void m1() {
System.out.println("Implemented once");
}
}
Only one implementation is required.
Case 2: Different Parameters
interface Left {
void m1();
}
interface Right {
void m1(int i);
}
class Test implements Left, Right {
public void m1() {
}
public void m1(int i) {
}
}
These become overloaded methods, so both implementations are required.
Case 3: Different Return Types
interface Left {
void m1();
}
interface Right {
int m1();
}
This is invalid because the same method signature cannot have different non-covariant return types.
Variable Naming Conflicts
Two interfaces may declare variables with the same name.
interface Left {
int x = 777;
}
interface Right {
int x = 888;
}
class Main implements Left, Right {
public static void main(String[] args) {
System.out.println(Left.x);
System.out.println(Right.x);
}
}
Output
777
888
The ambiguity is resolved by using the interface name.
Marker Interface in Java
A Marker Interface is an interface that contains no methods and no variables. Simply implementing it gives an object a special capability recognized by the JVM.
Popular Examples
| Marker Interface | Purpose |
|---|---|
| Serializable | Allows objects to be saved into files or transferred across a network. |
| Cloneable | Allows an object to create an exact duplicate using cloning. |
Serializable Example
Objects implementing Serializable can be:
- Saved into a file
- Sent across a network
- Stored for later use
Cloneable Example
Classes implementing Cloneable can create an exact copy of an existing object using cloning.
How can an interface without methods provide functionality?
The JVM internally recognizes marker interfaces and automatically provides the required behavior. This makes Java programming simpler while keeping the code clean.
Adapter Classes in Java
Suppose an interface contains ten methods, but your class only needs one of them. Without an adapter class, you'd still have to implement all ten methods.
An Adapter Class solves this problem by providing empty implementations for every method in an interface.
It is recommended to declare adapter classes as abstract.
Instead of writing unnecessary empty methods in every implementation class, you inherit them from a single abstract adapter class.
Example
interface Demo {
void m1();
void m2();
void m3();
}
abstract class DemoAdapter implements Demo {
public void m1() {
}
public void m2() {
}
public void m3() {
}
}
class Test extends DemoAdapter {
public void m2() {
System.out.println("Only required method");
}
}
How It Works
- Demo declares three methods.
- DemoAdapter provides empty implementations.
- Test overrides only the method it actually needs.
Advantages
- Reduces unnecessary code.
- Improves readability.
- Allows developers to override only required methods.
- Makes implementation cleaner and easier to maintain.
Interface vs Abstract Class
Both interfaces and abstract classes support abstraction, but they serve different purposes.
| Feature | Interface | Abstract Class |
|---|---|---|
| Purpose | Defines a contract | Provides partial implementation |
| Methods | Public abstract by default | Abstract + concrete methods |
| Variables | public static final | Instance, static, final |
| Constructors | Not allowed | Allowed |
| Inheritance | Multiple interfaces | Only one abstract class |
- Use an Interface when you want to define a common contract.
- Use an Abstract Class when multiple classes should share common code and state.
Why Do Abstract Classes Have Constructors but Interfaces Don't?
This is one of the most frequently asked Java interview questions.
Why Abstract Classes Have Constructors
Abstract classes can contain instance variables, which represent the object's state.
Whenever a child object is created, these variables need to be initialized.
Although we cannot directly create an abstract class object:
new Animal(); // Not allowed
its constructor is automatically executed through super().
Example
abstract class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
System.out.println("Dog constructor");
}
}
Creating an object:
new Dog();
Output
Animal constructor
Dog constructor
Execution Flow
- The Dog object is created.
- super() automatically calls the Animal constructor.
- The Animal constructor finishes.
- The Dog constructor executes.
Why Interfaces Don't Have Constructors
Interfaces do not maintain object state.
Every interface variable is already:
- public
- static
- final
These constants are initialized immediately when declared.
Since interfaces don't have instance variables, there is no object state to initialize, so constructors are unnecessary.
Quick Revision
- Marker interfaces provide special capabilities recognized by the JVM.
- Adapter classes provide empty implementations for interface methods.
- Interfaces define contracts, while abstract classes provide shared implementation.
- Abstract classes have constructors because they initialize object state.
- Interfaces don't need constructors because they don't have instance state.
Constructor Quiz (Interview Level)
Let's test your understanding with a common Java interview question.
Which of the following statements are correct?
- The purpose of a constructor is to create an object.
- The purpose of a constructor is to initialize an object, not create it.
- Object creation completes only after the constructor finishes.
- The object is created first, and then the constructor executes.
- The
newkeyword creates the object, while the constructor initializes it. - We cannot create an abstract class object directly, but we can indirectly create it through a child class.
- Whenever a child object is created, a parent object is automatically created internally.
- Whenever a child object is created, the abstract class constructor is executed automatically.
- Whenever a child object is created, the parent object is automatically created.
- Whenever a child object is created, the parent constructor executes, but a separate parent object is not created.
- Since we cannot create an abstract class object directly or indirectly, constructors are not applicable to abstract classes.
Correct Answers
Correct Options
2, 4, 5, 8, and 10
These are the statements commonly expected in Java interviews because they correctly explain the relationship between object creation, constructors, inheritance, and abstract classes.
Quick Interview Revision
Remember these one-liners
- Loose Coupling → Classes should have minimal dependencies.
- High Cohesion → One class should perform one responsibility.
- Interface → Defines a contract.
- implements → Used to implement interfaces.
- extends → Used for inheritance.
- Interface methods → Implicitly
public abstract. - Interface variables → Implicitly
public static final. - Marker Interface → Empty interface recognized by the JVM.
- Adapter Class → Provides empty implementations.
- Abstract Class → Can have constructors because it maintains object state.
- Interface → Doesn't have constructors because it has no instance state.
- new keyword → Creates the object.
- Constructor → Initializes the object.
Key Takeaways
Before moving on to advanced Java topics like Collections, Multithreading, and Spring Framework, make sure these OOP concepts become second nature.
- Write software with Loose Coupling and High Cohesion.
- Interfaces define requirements, while implementation classes provide behavior.
- A class can implement multiple interfaces.
- Interface methods are automatically
public abstract. - Interface variables are automatically
public static final. - Marker interfaces provide JVM-recognized capabilities.
- Adapter classes help reduce unnecessary code.
- Abstract classes can contain constructors because they initialize inherited state.
- The
newkeyword creates an object, while the constructor initializes it.
What's Next?
Now that you've mastered Interfaces, Coupling, Cohesion, and Abstract Classes, you're ready to explore more advanced Java topics.
☕ Continue Your Java Journey
Explore more beginner-friendly Java tutorials, interview questions, and complete roadmap articles.
Check More Java Blogs →RoadmapForJava
Learn Java step by step • Build strong fundamentals • Crack interviews with confidence
Comments
Post a Comment