KTU OOP Java2024 Scheme • 60M ESE
MODULE 3/Section 2: Interfaces

Interfaces: Defining, Implementing, Interface References & Partial Implementations

HIGH PRIORITY (Prep Guide)Official Syllabus~15 min study
Official KTU 2024 Syllabus Topics Covered Here
Introduction to interfacesDefining an interfaceImplementing interfacesimplements keywordAccessing implementations through interface references

1. Topic Introduction

An Interface takes abstraction to the next level by separating what a class must do from how it does it—completely detached from any class hierarchy! Even two totally unrelated classes (say Printer and Invoice) can implement the exact same Printable interface and be manipulated polymorphically through a single Printable reference.

2. Start From Zero: The USB Port Standard (Interface) & Different Devices (Implementations)

A USB specification defines exact pin shapes and signals (interface USBDevice { void transferData(); })—it doesn't build a mouse, flash drive, or printer itself. Any company that obeys that contract (implements USBDevice) plugs straight into your laptop's USB port (USBDevice port). Your laptop only knows port.transferData()—it doesn't know or care about any device's extra internal buttons!

Key Takeaway: Interfaces specify contracts (implements). Any implementing class MUST mark interface methods public. An interface reference (Callback c) can point to ANY implementing object, seeing ONLY the methods declared in the interface!

3. Essential Exam Definitions

Interface
A reference type declared with interface defining abstract method contracts, constants (public static final), and (since JDK 8) optional default/static methods, enabling unrelated classes to share polymorphic behavior.
Partial Implementation
A class that implements an interface without implementing all of its abstract methods; Java requires such a class to be declared abstract.
Nested Interface
An interface declared as a member inside a class or another interface; unlike top-level interfaces (public or default), nested interfaces inside a class can be public, private, or protected.

4. Detailed Technical Explanation & Syntax

1. Defining & Implementing an Interface

Syntax: access interface InterfaceName { type var = value; returnType method(params); }.

Implicit Modifiers: Every field in an interface is implicitly public static final (constant—MUST be initialized at declaration!). Every abstract method is implicitly public abstract.

Implementation Rule: A class uses implements I1, I2 (comma-separated for multiple interfaces). Every implemented interface method MUST be declared **public** in the implementing class (because interface methods are implicitly public, and Java forbids weakening access!).

2. Accessing Implementations Through Interface References (Classic Exam Example!)

From your lecture notes (Callback / Client / AnotherClient): you can declare a variable of an interface type (Callback c = new Client();). Any instance of ANY implementing class can be assigned to c, achieving runtime polymorphism!

Crucial Restriction: An interface reference c has knowledge ONLY of the methods declared inside Callback—calling a class-specific helper like c.nonIfaceMeth() defined only in Client causes a COMPILE ERROR!

3. Variables in Interfaces (Shared Constants) & Nested Interfaces

Interfaces can export shared constants (interface SharedConstants { int NO = 0; int YES = 1; }) so multiple implementing classes inherit constants cleanly without repeating magic numbers.

A Nested Interface declared inside a class A (class A { public interface NestedIF { boolean isNotNegative(int x); } }) is qualified externally as A.NestedIF.

5. Working Principle: Runtime Polymorphism via Interface Reference

  1. 1. Callback c = new Client(); c.callback(42); -> JVM dispatches Client.callback(42).
  2. 2. c = new AnotherClient(); c.callback(42); -> same variable c dynamically dispatches AnotherClient.callback(42)!

7. Complete Java Code Examples & Tracing

Interface Reference Polymorphism (`Callback` & `Client`) + Constants + Nested InterfaceInterfaceReferenceDemo.java
Complete runnable demo based directly on the lecture's Callback/Client/AnotherClient design, showing interface reference dispatch and nested interface syntax.
1interface Callback {
2 int DEFAULT_PARAM = 42; // Implicitly public static final
3 void callback(int param);
4}
5
6class Client implements Callback {
7 @Override
8 public void callback(int p) { // Must be public!
9 System.out.println("Client.callback called with: " + p);
10 }
11
12 void nonIfaceMethod() {
13 System.out.println("Classes implementing interfaces may define extra members.");
14 }
15}
16
17class AnotherClient implements Callback {
18 @Override
19 public void callback(int p) {
20 System.out.println("AnotherClient version -> p squared = " + (p * p));
21 }
22}
23
24class OuterHolder {
25 public interface NestedIF {
26 boolean isPositive(int x);
27 }
28}
29
30class Checker implements OuterHolder.NestedIF {
31 @Override
32 public boolean isPositive(int x) {
33 return x >= 0;
34 }
35}
36
37public class InterfaceReferenceDemo {
38 public static void main(String[] args) {
39 Callback c = new Client();
40 c.callback(Callback.DEFAULT_PARAM);
41 // c.nonIfaceMethod(); // COMPILE ERROR: Callback ref doesn't know nonIfaceMethod()!
42
43 AnotherClient ob = new AnotherClient();
44 c = ob; // Same interface ref now points to AnotherClient
45 c.callback(5);
46
47 OuterHolder.NestedIF nif = new Checker();
48 System.out.println("Is 10 positive? " + nif.isPositive(10));
49 }
50}
Expected Output
Client.callback called with: 42
AnotherClient version -> p squared = 25
Is 10 positive? true
Keywords:interfaceimplementspublic@Override
Common Exam & Coding Mistakes
  • Omitting public on void callback(int p) in Client (defaults to package-private, failing compilation!).
  • Attempting to call c.nonIfaceMethod() using an interface reference Callback c.
  • Declaring an uninitialized field inside an interface (interface fields are final, so initialization is mandatory).

Real-World Applications

  • ActionListener in Swing, Comparable<T> for sorting, and Connection/Statement in JDBC are all Java interfaces!

Important KTU Exam Points

  • Remember: Interface reference sees ONLY methods declared in the interface—never extra subclass methods!
  • Always state what happens on Partial Implementation: the implementing class MUST be declared abstract.

Memory Techniques & Revision

  • Interface Members = 'P-S-F Variables, P-A Methods': public static final vars, public abstract methods!

Common Pitfalls to Avoid

  • Forgetting public when implementing an interface method.

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: Java allows declaring reference variables of an interface type (Callback c;) to refer to objects of any class implementing that interface, supporting runtime dynamic method resolution.

  • An interface variable c can hold references to unrelated classes implementing the same interface (Client, AnotherClient).
  • Calling c.callback(p) executes the version belonging to the actual runtime object.
  • Limitation: Through c, only methods declared in the interface are accessible; class-specific non-interface methods cannot be called directly via c.
Callback c = new Client();
c.callback(10);
c = new AnotherClient();
c.callback(10);

Quick Understanding Check

1. If class PartialImpl implements Callback does NOT implement callback(), what must be true?