Nearby lessons

43 of 125

Java - Interfaces

📌 What You Will Learn
  • What class and object mean, with real-life examples
  • The four pillars: Encapsulation, Abstraction, Inheritance, Polymorphism
  • Constructors, this, super, static and final
  • Method overloading and method overriding (with a comparison table)
  • Abstract classes and interfaces (including the modern changes)
  • Association, Aggregation and Composition

Interfaces is a core concept of the Java language. This lesson explains Interface — The Full Rules and Class vs Abstract Class vs Interface — Master Table with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Interface — The Full Rules

In the classic Java (before Java 8), an interface had these defaults:

  • Every variable in an interface is public static final automatically — you do not write it.
  • Every method in an interface is public abstract automatically.
  • Interfaces cannot have constructors.
  • You cannot create an object of an interface — only a reference variable.
Example01
JCode Cell
1interface I {
2 int x = 20; // really: public static final int x = 20;
3 void m1(); // really: public abstract void m1();
4}
5 
6class A implements I {
7 public void m1() { System.out.println("m1-A"); }
8 public void m4() { System.out.println("m4-A"); }
9}
10 
11class Test {
12 public static void main(String[] args) {
13 I i = new A(); // interface reference, class object
14 i.m1();
15 // i.m4(); // ERROR - m4 is not in the interface
16 
17 System.out.println(I.x); // static: accessed by interface name
18 System.out.println(i.x); // or by reference
19 }
20}

Class vs Abstract Class vs Interface — Master Table

PointClassAbstract classInterface
Concrete methodsAllowedAllowedNot (classically)
Abstract methodsNot allowedAllowedAllowed
Keywordclassabstract classinterface
ObjectsYesNo (only references)No (only references)
Variables defaultNo defaultNo defaultpublic static final
Methods defaultNo defaultNo defaultpublic abstract
ConstructorsAllowedAllowedNot allowed
SharabilityLessMediumMost
📝 Key Takeaways
  • Class = blueprint; Object = real thing made from it (memory in heap).
  • Four pillars: Encapsulation (hide data), Abstraction (show only essentials), Inheritance (reuse parent code), Polymorphism (one name, many forms).
  • Overloading = same class, different parameters, decided at compile time. Overriding = child redefines parent method, decided at run time.
  • Constructor initialises the object; name = class name, no return type.
  • this = current object; super = parent class; static = belongs to class; final = cannot change.
  • abstract class cannot be instantiated; interface is a contract a class implements.
  • Association (weak), Aggregation (has-a, part independent), Composition (strong has-a, part dies with whole).

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1