Core Java Training
Day 7
Topics
Abstraction
• abstract classes
• interfaces
Abstraction in Java
Abstraction is the process of hiding internal implementation and showing only essential
features to the user.
It allows to focus on what an object does rather than how it does it. The unnecessary details
are not displayed to the user.
Real-Life Analogy - TV Remote Control: Why Use Abstraction?
▪ You know what buttons to press •To define a common structure or contract
(volumeUp(), powerOn()). •To reduce complexity by hiding low-level
▪ You don’t know how the circuit logic
works internally. •To decouple implementation from usage
That’s abstraction — only important things
are exposed, unnecessary details are
hidden.
Abstraction in Java
Java provides two ways to implement abstraction, which are listed below:
▪ Abstract Classes (Partial Abstraction)
▪ Interface (100% Abstraction)
1. Abstract Classes: An abstract class is a class that you can’t instantiate and can only extend
by subclasses. Abstract classes can have both abstract and non-abstract methods. Abstract
methods do not have a body and you must implement them by any subclass that extends
the abstract class. Non-abstract methods have a body and you can directly call them by the
subclass.
2. Interfaces: An interface is a collection of methods. You can use it to define a set of behaviors
that a class should implement. A class can implement multiple interfaces, and all the
methods defined in an interface must be implemented by any class that implements it.
Abstraction in Java
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class:
Real-World Problem : Online Payment Gateway
You are designing an online shopping app. Users can pay via Credit Card, UPI, or Wallet. You want to
define a common structure, but let each payment type handle its own logic.
Step 1: Abstract Class – Payment
abstract class Payment {
double amount;
Payment(double amount) {
this.amount = amount;
}
abstract void makePayment(); // abstract method
void generateReceipt() {
System.out.println("Receipt generated for ₹" +
amount);
}
}
Real-World Java Problem : Online Payment Gateway
Step 2: Subclasses – CreditCardPayment, UPIPayment, etc.
class CreditCardPayment extends Payment { class UPIPayment extends Payment {
CreditCardPayment(double amount) { UPIPayment(double amount) {
super(amount); super(amount);
} }
@Override @Override
void makePayment() { void makePayment() {
System.out.println("Paying ₹" + amount System.out.println("Paying ₹" +
+ " using Credit Card..."); amount + " using UPI...");
} }
} }
Real-World Java Problem : Online Payment Gateway
Step 3: Driver Code – Main Class
public class Main {
public static void main(String[] args) {
Payment p1 = new CreditCardPayment(500.00);
p1.makePayment();
p1.generateReceipt();
Payment p2 = new UPIPayment(300.00);
p2.makePayment();
p2.generateReceipt();
}
}
Problem Statement:
Design and implement a Java-based Library Management System using Object-Oriented
Programming concepts. Functional Requirements:
• Add books to library
• Register new member (Student/Faculty)
• Issue book to member (check max limit)
• Return book
• List all books
• List all issued books
Tips:
• Use Interfaces like Loanable, Displayable
• Create Exception handling for invalid book issue
• Track number of books issued per member
• Use toString() to format object output
Practice Questions:
Q1. Which of the following is true about abstract classes in Java?
A, You can instantiate an abstract class directly
B. Abstract classes can have constructors.
C. Abstract methods must have a body
D. Abstract class can't have implemented methods
Q2. What happens if a class contains an abstract method but is not declared abstract?
A. It runs successfully
B. Compiler error
C. Runtime error
D. The method is ignored
Q3. Can you declare an abstract method as static?
A. Yes
B. No
C. Only from Java 9
D. Only inside interfaces
Practice Questions:
Q4. Which of these modifiers cannot be used with an abstract method?
A. public
B. protected
C. private
D. abstract
Q5. Which of these is a valid way to use an abstract class?
A. Instantiate it directly
B. Extend it and override abstract methods
C. Use it to create constants
D. Implement it like an interface
Q6. Can an abstract class implement an interface without providing method
implementations?
A. Yes
B. No
C. Only if the class is final
D. Only in Java 8+
Practice Questions:
Q7. What will happen if a subclass of an abstract class doesn't implement all abstract
methods?
A. Compilation error
B. Program runs with warnings
C. It becomes an abstract class itself
D. JVM adds method definitions automatically
Q8. Which statement is true for an abstract class in Java?
A. It must have at least one abstract method
B. It cannot have any constructors
C. It can have both abstract and non-abstract methods
D. It must implement all interfaces
Q9. Abstract classes are primarily used for:
A. Preventing inheritance
B. Hiding class variables
C. Providing a base for subclasses with default behavior
D. Improving performance
Practice Questions:
class Animal {
void speak() {
System.out.println("Animal speaks");
What will be the output?
}
}
A. Animal speaks class Dog extends Animal {
B. Dog barks
void speak() {
super.speak();
C. Animal speaks
System.out.println("Dog barks");
}
Dog barks }
D. Compilation error public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.speak();
}
}
Practice Questions:
abstract class Shape {
Shape() {
System.out.println("Shape constructor
What will be printed?
called");
}
A. Shape constructor called }
B. Circle constructor called class Circle extends Shape {
C. Shape constructor called Circle() {
Circle constructor called
System.out.println("Circle constructor
called");
D. Nothing }
}
public class Main {
public static void main(String[] args) {
Circle c = new Circle();
}
}
Practice Questions:
class Print {
void show(int a) {
System.out.println("Integer: " + a);
Which OOP concept is used here?
}
A. Overriding
void show(String s) {
B. Polymorphism (Compile-time)
System.out.println("String: " + s);
C. Abstraction }
}
D. Encapsulation
public class Test {
public static void main(String[] args) {
Print p = new Print();
p.show("Java");
p.show(10);
}
}
Practice Questions:
interface A {
default void greet() {
System.out.println("Hello from A");
}
}
What will be the output? interface B {
default void greet() {
A. Hello from A
System.out.println("Hello from B");
Hello from B }
}
Hello from MyClass class MyClass implements A, B {
public void greet() {
B. Hello from MyClass A.super.greet();
B.super.greet();
C. Compilation error System.out.println("Hello from MyClass");
}
D. Hello from A }
public class Test {
public static void main(String[] args) {
new MyClass().greet();
}
}
Practice Questions:
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
What does this code demonstrate?
public String getName() {
A. Inheritance return name;
B. Polymorphism
}
}
C. Encapsulation
public class Test {
D. Abstraction public static void main(String[] args) {
Person p = new Person();
p.setName("Ravi");
System.out.println(p.getName());
}
}
Practice Questions:
class Student {
int id;
What is the purpose of this in
String name;
constructor? Student(int id, String name) {
this.id = id;
A. Refers to the base class this.name = name;
B. B. Refers to current class object
}
C. C. Refers to local variable
void display() {
System.out.println(id + " " +
D. D. None of the above name);
}
}
Key tips abstract classes
1. An instance of an abstract class can not be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract method.
4. There can be a final method in abstract class but any abstract method in class(abstract
class) can not be declared as final or in simpler terms final method can not be abstract
itself as it will yield an error: "Illegal combination of modifiers: abstract and final"
5. We can define static methods in an abstract class
6. We can use the abstract keyword for declaring top-level classes (Outer class) as well as
inner classes as abstract
7. If a class contains at least one abstract method then compulsory should declare a class
as abstract
8. If the Child class is unable to provide implementation to all abstract methods of
the Parent class then we should declare that Child class as abstract so that the next level
Child class should provide implementation to the remaining abstract method
Interface
A completely abstract type used to specify a contract — what a class must do, but not how.
To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends).
interface Animal { public void sleep() {
public void animalSound(); // interface // The body of sleep() is provided
method (does not have a body) here
public void sleep(); // interface method System.out.println("Zzz");
(does not have a body) }
} }
// Pig "implements" the Animal interface class Main {
class Pig implements Animal { public static void main(String[]
public void animalSound() { args) {
// The body of animalSound() is Pig myPig = new Pig(); // Create a
provided here Pig object
System.out.println("The pig says: wee myPig.animalSound();
wee"); myPig.sleep();
} } }
Key Features of Java
Multiple Interfaces: To implement multiple interfaces, separate them with a comma:
interface FirstInterface { public void myOtherMethod() {
public void myMethod(); // interface method System.out.println("Some other text...");
} }
}
interface SecondInterface {
public void myOtherMethod(); // interface method class Main {
} public static void main(String[] args) {
DemoClass myObj = new DemoClass();
class DemoClass implements FirstInterface, SecondInterface myObj.myMethod();
{ myObj.myOtherMethod();
public void myMethod() { }
System.out.println("Some text.."); }
}
Difference b/w Abstract and Interface
Feature Abstract Class Interface
Keyword Used abstract class interface
Method Types Both abstract and concrete methods Only abstract (Java 7), from Java 8:
default & static methods
Fields (Variables) Can have instance variables with All variables are public static final
access modifiers (constants)
Constructors Yes No constructors
Multiple Inheritance Not allowed (Java doesn't support it A class can implement multiple
with classes) interfaces
Access Modifiers Allowed public, protected, private Only public (everything is implicitly
public abstract)
Performance Slightly faster Slightly slower due to indirection
(especially older versions)
When to Use When classes share common When unrelated classes must follow
behavior/fields same contract
Java Version Enhancements Minor additions Java 8+: default, static methodsJava
9+: private methods
Key Features of Java