Abstraction means showing what an object can do while hiding how. Java gives you two tools: abstract classes and interfaces.
Abstract classes#
An abstract class cannot be instantiated. It can contain abstract methods (no body) that every concrete subclass must implement, along with normal fields and methods:
Meera (Savings): 52000.00 Om (FixedDeposit): 214200.00
Abstract class एक अधूरा नक्शा है - इसमें कुछ methods का सिर्फ़ नाम होता है (abstract), body नहीं। इसका object नहीं बनता। Child class को वो methods पूरे करने ही पड़ते हैं। इससे सब child classes एक जैसा "contract" मानती हैं, पर हर एक अपने तरीके से काम करती है।
Interfaces#
An interface is a pure contract: a set of methods a class promises to provide. A class implements an interface and must define all its abstract methods. A class can implement many interfaces - this is how Java gets multiple inheritance of type safely.
Printing document... Inkjet printing in colour Got scanned-page.pdf
Interface methods are implicitly public abstract, and interface fields are implicitly public static final (constants).
default and static methods in interfaces#
Since Java 8, interfaces can have default methods (with a body, inherited by implementers) and static helper methods:
Java Full Stack: 20000.0 + GST 3600.0
Comparable - an interface you will use constantly#
Implementing Comparable<T> gives a class a natural order, so Arrays.sort and Collections.sort can sort it:
[Nisha(9.47), Kabir(9.16), Yash(7.78)]
Functional interfaces#
An interface with exactly one abstract method is a functional interface and can be implemented with a lambda (covered in the Lambdas lesson):
12 1024
Abstract class or interface?#
| Abstract class | Interface | |
|---|---|---|
| Instance fields (state) | yes | no (only constants) |
| Constructors | yes | no |
| Method bodies | yes | default/static/private methods only |
| How many can a class use | one (extends) |
many (implements) |
| Best for | closely related classes sharing code and state | capabilities shared by unrelated classes (Comparable, Runnable, Printable) |
A common design: an interface for the contract (Payment), an optional abstract class for shared code (AbstractPayment), and concrete classes (UpiPayment, CardPayment). Program against the interface type.
Summary#
abstractclasses can't be instantiated and may contain abstract (bodiless) methods that subclasses must implement.- Interfaces define contracts; a class can implement many; they can have default and static methods.
Comparablegives natural ordering; one-method interfaces can be implemented with lambdas.- Use an abstract class for shared state/code, an interface for shared capability.