0% found this document useful (0 votes)
3 views28 pages

Java Inheritance Polymorphism Abstract Interface

The document covers Java programming concepts focusing on inheritance, polymorphism, abstract classes, and interfaces. It includes a 14-day study plan with coding exercises, detailed notes on inheritance types, method overriding, and the use of the super keyword. Additionally, it provides viva questions and coding problems for practice and understanding of the material.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views28 pages

Java Inheritance Polymorphism Abstract Interface

The document covers Java programming concepts focusing on inheritance, polymorphism, abstract classes, and interfaces. It includes a 14-day study plan with coding exercises, detailed notes on inheritance types, method overriding, and the use of the super keyword. Additionally, it provides viva questions and coding problems for practice and understanding of the material.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

☕ JAVA PROGRAMMING

Inheritance & Polymorphism · Abstract Classes & Interfaces

Topics Covered
Unit 1 → Inheritance – Types, Syntax, IS-A Relationship
Unit 2 → Method Overriding & Runtime Polymorphism
Unit 3 → super Keyword – All Uses
Unit 4 → Object Class – toString() & equals() Override
Unit 5 → final Keyword – Class, Method, Variable
Unit 6 → instanceof Operator
Unit 7 → Abstract Classes & Abstract Methods
Unit 8 → Interfaces – static & default Methods

Detailed Notes • 14-Day Study Plan • Viva Q&A (Easy → Hard) • Coding Problems
📅 Study Plan – 14 Days
1.5 – 2 hours per day. Code every example you read. Don't just memorize — understand WHY.

Day Topic What To Do Revise


Day Inheritance Basics Write 3 parent-child class pairs; test —
1 extends, field access
Day Types of Single → Multilevel → Hierarchical — code Day 1
2 Inheritance all 3 types
Day Method Overriding Override 5 different parent methods; Day 2
3 observe dynamic dispatch
Day super keyword Use all 3 super uses: variable, method call, Day 3
4 constructor
Day Object class Override toString() and equals() in 3 Day 4
5 custom classes
Day final keyword Mark final var, method, class — attempt Day 5
6 overriding to see error
Day instanceof operator Test instanceof in class hierarchy; use for Days 1–6
7 safe casting
Day Polymorphism Upcasting, downcasting, dynamic method Day 7
8 deep dive dispatch — 4 programs
Day Abstract Class Write abstract class + 2 concrete Day 8
9 subclasses; no instantiation
Day Abstract vs Template method pattern; partial Day 9
10 Concrete implementation in abstract
Day Interface basics Declare interface; implement in 2 classes; Day 10
11 multiple implementation
Day Interface – static & Add static util method, default method with Day 11
12 default override
Day Abstract class vs Write same design both ways; compare Days 9–12
13 Interface trade-offs
Day Full Mock + Viva Answer all viva Qs aloud; solve 2 coding All
14 Practice Qs per unit timed
📘 Unit 1: Inheritance
1.1 What is Inheritance?
Inheritance is an OOP mechanism where a child class (subclass) acquires the properties and
behaviours of a parent class (superclass). It models the IS-A relationship and promotes code reuse.
Term Also Called Created With
Parent Class Superclass / Base class class Parent { }
Child Class Subclass / Derived class class Child extends Parent { }

Key Rule: A child class inherits all non-private members (fields and methods) of its parent
class.

1.2 extends Keyword


class Animal { // Parent
String name;
void eat() { [Link](name + " is eating"); }
}

class Dog extends Animal { // Child — inherits name, eat()


void bark() { [Link](name + " is barking"); }
}

// Main
Dog d = new Dog();
[Link] = "Tommy";
[Link](); // inherited from Animal
[Link](); // own method

1.3 Types of Inheritance in Java

Type Description Supported in Java?


Single One parent → one child ✅ Yes
Multilevel A → B → C (chain) ✅ Yes
Hierarchical One parent → multiple children ✅ Yes
Multiple (class) One child → two parent classes ❌ Not with classes
Multiple (interface) One class implements two interfaces ✅ Yes (via interfaces)
Hybrid Combination of above types ✅ Partially (via interfaces)

Java does NOT support multiple inheritance through classes to avoid the Diamond Problem
— ambiguity when two parents have the same method.

① Single Inheritance
class Vehicle { void start() { [Link]("Started"); } }
class Car extends Vehicle { void drive() { [Link]("Driving"); } }

② Multilevel Inheritance
class Animal { void breathe() { [Link]("Breathing"); } }
class Mammal extends Animal { void feedMilk() { } }
class Human extends Mammal { void speak() { } }
// Human inherits: breathe() + feedMilk() + speak()

③ Hierarchical Inheritance
class Shape { void draw() { [Link]("Drawing shape"); } }
class Circle extends Shape { void drawCircle() { } }
class Rectangle extends Shape { void drawRectangle() { } }
class Triangle extends Shape { void drawTriangle() { } }

1.4 What is Inherited? What is NOT?


Inherited ✅ NOT Inherited ❌
public fields & methods private fields & methods
protected fields & methods Constructors
Default (package-private) — if same package static members (not inherited, but accessible)

1.5 IS-A vs HAS-A


Relationship Name Example Java Mechanism
IS-A Inheritance Dog IS-A Animal extends / implements
HAS-A Composition / Car HAS-A Engine Object as a field
Aggregation

1.6 Viva Questions – Unit 1


[Easy] What is inheritance?
Ans: A mechanism where a subclass acquires fields and methods of a superclass. Models IS-A
relationship and promotes code reuse.
[Easy] What keyword is used to inherit a class?
Ans: extends keyword. Syntax: class Child extends Parent { }
[Easy] What types of inheritance does Java support?
Ans: Single, Multilevel, and Hierarchical. Multiple inheritance through classes is NOT supported.
[Medium] Why doesn't Java support multiple inheritance through classes?
Ans: To avoid the Diamond Problem — if two parent classes have the same method, the child class would
be ambiguous about which one to use.
[Medium] Are constructors inherited?
Ans: No. Constructors are not inherited. However, the parent constructor is called via super() (implicitly or
explicitly).
[Medium] Are private members inherited?
Ans: Private members are NOT directly inherited/accessible in the child class. They exist in the object but
are hidden.
[Hard] What is the Diamond Problem?
Ans: When class D extends B and C, and both B and C extend A with the same method — D doesn't
know which version to use. Java avoids this by prohibiting multiple class inheritance.
[Hard] Can a subclass access private members of the superclass?
Ans: Not directly. But through public/protected getter methods defined in the parent class.

1.7 Coding Questions – Unit 1


Q1. Create a Vehicle → Car → ElectricCar multilevel inheritance. Add a unique method at each level.
Hint: Vehicle: fuel(), Car: drive(), ElectricCar: charge()
Q2. Demonstrate hierarchical inheritance: Shape as parent, Circle, Square, Triangle as children each
with their own area() method.
Hint: Shape has abstract-like structure, each child overrides area()
Q3. Create an Employee class with name and salary. Create Manager that extends Employee and
adds a department field.
Hint: Test object creation for both and access inherited fields
Q4. Show that private members are NOT accessible in child class. Fix using getter.
Hint: Try [Link] → error; use [Link]() → works
📗 Unit 2: Method Overriding & Runtime
Polymorphism
2.1 What is Method Overriding?
When a subclass provides its OWN implementation of a method already defined in the superclass —
with the SAME name, SAME return type, and SAME parameter list.
Rule Detail
Same method signature Name, parameters, and return type must match exactly
IS-A required Class must extend the parent (inheritance needed)
Access modifier Cannot be more restrictive than parent (can be broader)
Return type Must be same OR covariant (subtype of parent return type)
static methods Cannot be overridden — only hidden (method hiding)
final methods Cannot be overridden
private methods Cannot be overridden (not visible to child)
@Override annotation Recommended — compiler verifies the override is valid

2.2 Method Overriding Example


class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() { // overrides Animal's sound()
[Link]("Dog barks: Woof!");
}
}

class Cat extends Animal {


@Override
void sound() {
[Link]("Cat meows: Meow!");
}
}

2.3 Runtime Polymorphism (Dynamic Method Dispatch)


When a parent class reference variable holds a child class object, and a method is called — the
ACTUAL object's version runs (not the reference type's). Resolved at runtime.
// Upcasting — parent reference, child object
Animal a;
a = new Dog(); [Link](); // Dog barks: Woof!
a = new Cat(); [Link](); // Cat meows: Meow!

// The method called depends on the OBJECT TYPE, not reference type
Animal[] zoo = { new Dog(), new Cat(), new Dog() };
for (Animal x : zoo) {
[Link](); // dynamic dispatch — correct version called
}

Runtime Polymorphism = One interface (Animal reference), multiple implementations (Dog,


Cat, etc.) — method resolved at runtime, NOT compile time.

2.4 Upcasting vs Downcasting


Type Definition Automatic? Risk
Upcasting Child object → Parent Yes (implicit) No risk
reference
Downcasting Parent reference → Child No (explicit cast ClassCastException if
reference needed) wrong

Animal a = new Dog(); // Upcasting — automatic


Dog d = (Dog) a; // Downcasting — explicit
// Cat c = (Cat) a; // ClassCastException at runtime!

// Safe downcasting using instanceof


if (a instanceof Dog) {
Dog d2 = (Dog) a;
[Link]();
}

2.5 Covariant Return Types


Overriding method CAN return a subtype of the parent method's return type (Java 5+).
class Animal { Animal create() { return new Animal(); } }
class Dog extends Animal {
@Override
Dog create() { return new Dog(); } // Dog IS-A Animal — valid!
}

2.6 Overriding vs Overloading – Full Comparison


Aspect Overriding Overloading
Definition Same signature in parent & child Same name, different params in same class
Polymorphism Runtime (Dynamic) Compile-time (Static)
@Override Recommended (verified) Not applicable
Inheritance Required Not required
Return type Same or covariant Can be different
Access modifier Cannot narrow Can be anything
static/final methods Cannot be overridden Can be overloaded
2.7 Viva Questions – Unit 2
[Easy] What is method overriding?
Ans: Providing a specific implementation of a method in the child class that is already defined in the
parent class with same name, return type, and parameters.
[Easy] What is @Override annotation? Is it mandatory?
Ans: It tells the compiler to verify that the method is actually overriding a parent method. Not mandatory
but strongly recommended — catches typo errors.
[Medium] What is Runtime Polymorphism?
Ans: Also called Dynamic Method Dispatch. Method call is resolved at runtime based on the actual object
type, not the reference type.
[Medium] Can we override a static method?
Ans: No. Static methods are resolved at compile time based on reference type — this is called method
hiding, not overriding.
[Medium] Can we override a private method?
Ans: No. Private methods are not visible to subclasses, so they cannot be overridden. The child class may
define a same-name method but it's a NEW method, not an override.
[Medium] What is upcasting and downcasting?
Ans: Upcasting: assigning child object to parent reference (implicit, safe). Downcasting: casting parent
reference back to child type (explicit, may throw ClassCastException).
[Hard] What is covariant return type?
Ans: An overriding method can return a subtype of the parent method's return type. E.g., parent returns
Animal, child can return Dog.
[Hard] If a parent and child both have a static method with same name, what happens?
Ans: Method hiding occurs, not overriding. The method called depends on the REFERENCE type, not the
object type.

2.8 Coding Questions – Unit 2


Q1. Create a Shape hierarchy (Shape, Circle, Rectangle, Triangle) — override area() in each. Store in
Shape[] and call area() for each.
Hint: Dynamic dispatch: Shape[] shapes = {new Circle(5), new Rectangle(3,4)};
Q2. Demonstrate upcasting and safe downcasting using instanceof before cast.
Hint: Animal a = new Dog(); if(a instanceof Dog) { Dog d = (Dog)a; }
Q3. Show that @Override catches a typo: misspell the method name and observe the compile error.
Hint: @Override on soound() vs sound() in parent
Q4. Create a Payment system: Payment (parent) with processPayment(). CreditCard, UPI, NetBanking
each override it.
Hint: Call all via Payment reference — runtime polymorphism
📙 Unit 3: super Keyword
3.1 What is super?
super is a reference to the immediate parent class object. It is used to access parent class members
(fields, methods, constructors) that are hidden or overridden.
Use Syntax Purpose
1. Access parent field [Link] When child has same-name field
2. Call parent method [Link]() When method is overridden in child
3. Call parent super(args) Must be FIRST line in child constructor
constructor

3.2 Use 1 — Access Parent Field


class Animal {
String type = "Animal";
}
class Dog extends Animal {
String type = "Dog";

void show() {
[Link]([Link]); // Animal
[Link]([Link]); // Dog
}
}

3.3 Use 2 — Call Parent (Overridden) Method


class Animal {
void sound() { [Link]("Generic animal sound"); }
}
class Dog extends Animal {
@Override
void sound() {
[Link](); // calls Animal's sound()
[Link]("Woof!"); // Dog's own behaviour
}
}

3.4 Use 3 — Call Parent Constructor


class Person {
String name;
int age;
Person(String name, int age) {
[Link] = name;
[Link] = age;
}
}
class Student extends Person {
int rollNo;
Student(String name, int age, int rollNo) {
super(name, age); // MUST be first statement
[Link] = rollNo;
}
void display() {
[Link](name + " | " + age + " | " + rollNo);
}
}

If you don't write super() explicitly, Java automatically inserts super() (no-arg) as the first
statement. If the parent has NO no-arg constructor, you MUST write super(args) manually.

3.5 Implicit super() Call


class A {
A() { [Link]("A constructor"); }
}
class B extends A {
B() {
// super() inserted automatically by compiler
[Link]("B constructor");
}
}
// Output: A constructor → B constructor

3.6 super vs this — Complete Comparison


Feature super this
Refers to Immediate parent class Current class instance
Field access [Link] — parent's field [Link] — current field
Method call [Link]() — parent's [Link]() — current version
version
Constructor super() — parent constructor this() — another constructor in same class
First statement rule super() must be first in this() must be first in constructor
constructor
Both in same NO — only one allowed (both NO
constructor? need first line)

3.7 Viva Questions – Unit 3


[Easy] What is the super keyword?
Ans: A reference to the immediate parent class. Used to access parent fields, call parent methods, and
invoke parent constructors.
[Easy] What are the 3 uses of super?
Ans: 1) Access parent field ([Link]). 2) Call overridden parent method ([Link]()). 3) Call parent
constructor (super(args)) — must be first line.
[Medium] Is super() automatically inserted?
Ans: Yes. If no explicit super() or this() call exists, Java inserts super() (no-arg) as the first statement
automatically.
[Medium] What happens if the parent has no no-arg constructor and child doesn't call super(args)?
Ans: Compile error — Java tries to insert super() automatically but fails because no matching no-arg
constructor exists in the parent.
[Medium] Can super and this() both appear in one constructor?
Ans: No. Both must be the first statement. Only one can appear per constructor.
[Hard] Can super be used in a static method?
Ans: No. super refers to an instance of the parent. Static methods have no instance context.
[Hard] If class C extends B extends A, and C calls [Link](), which method runs?
Ans: B's method runs (immediate parent). To reach A's method, B would need to call [Link]() in its
own method.

3.8 Coding Questions – Unit 3


Q1. Employee (name, salary) → Manager (department). Use super(name,salary) in Manager
constructor. Display all fields.
Hint: super call in child constructor to initialize parent fields
Q2. Animal → Dog. Override sound() in Dog. Inside Dog's sound(), call [Link]() first, then print
'Woof!'
Hint: Extending parent behaviour using [Link]()
Q3. Vehicle → Car → SportsCar multilevel. In each constructor use super(). Show the full chain of
constructor calls.
Hint: Print inside each constructor to trace the call order
Q4. Parent and Child both have a field 'name'. Inside Child, print both using [Link] and
[Link].
Hint: Show field shadowing resolution
📒 Unit 4: Object Class – toString() and equals()
4.1 The Object Class
[Link] is the root of the Java class hierarchy. Every class in Java implicitly extends Object. It
provides 11 fundamental methods that all classes inherit.
Method Description
toString() Returns String representation of object
equals(Object o) Checks logical equality
hashCode() Returns hash code (integer) of object
getClass() Returns runtime class of object
clone() Creates a copy of the object (shallow)
finalize() Called by GC before object is collected (deprecated)
wait() / notify() / notifyAll() Thread synchronization methods

4.2 Default toString()


Without override, toString() returns: ClassName@HexHashCode — not useful for display.
class Student {
String name; int age;
Student(String name, int age) { [Link]=name; [Link]=age; }
}
Student s = new Student("Shivam", 20);
[Link](s); // Student@1b6d3586 ← not readable

4.3 Overriding toString()


class Student {
String name; int age;
Student(String name, int age) { [Link]=name; [Link]=age; }

@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
}
[Link](s); // Student{name='Shivam', age=20}

toString() is called automatically by [Link](obj) and String concatenation ("" +


obj). Always override it for meaningful output.

4.4 Default equals()


Without override, equals() uses == — compares references (memory addresses), not content.
Student s1 = new Student("Alice", 20);
Student s2 = new Student("Alice", 20);
[Link](s1 == s2); // false (different objects)
[Link]([Link](s2)); // false (uses == by default)

4.5 Overriding equals()


@Override
public boolean equals(Object obj) {
if (this == obj) return true; // same reference
if (obj == null) return false; // null check
if (getClass() != [Link]()) // type check
return false;
Student other = (Student) obj; // safe cast
return [Link] == [Link] && // field comparison
[Link]([Link]);
}

// Now:
[Link]([Link](s2)); // true ✅

4.6 equals() and hashCode() Contract


CONTRACT: If [Link](b) is true, then [Link]() MUST equal [Link]().
• Always override hashCode() whenever you override equals()
• If two objects are equal, they must have the same hash code
• If two objects have the same hash code, they are NOT necessarily equal
@Override
public int hashCode() {
return [Link](name, age); // from [Link]
}

4.7 Viva Questions – Unit 4


[Easy] What is the Object class?
Ans: The root class of all Java classes. Every class implicitly extends [Link]. It provides
methods like toString(), equals(), hashCode(), getClass(), etc.
[Easy] What does the default toString() return?
Ans: ClassName@HexadecimalHashCode. e.g., Student@1b6d3586. Not human-readable — should be
overridden.
[Easy] What does the default equals() do?
Ans: Compares object references (like ==). Returns true only if both variables point to the same object in
memory.
[Medium] Why should we override both equals() and hashCode() together?
Ans: The contract: if two objects are equal (equals() returns true), they must have the same hashCode().
Breaking this causes bugs in HashMap, HashSet, etc.
[Medium] What are the steps in a proper equals() override?
Ans: 1) Check if same reference (this == obj). 2) Null check. 3) Check class type. 4) Cast. 5) Compare
fields.
[Medium] When is toString() called implicitly?
Ans: When you pass an object to [Link](), use string concatenation ("" + obj), or in logging
statements.
[Hard] Can equals() accept a parameter of the child class instead of Object?
Ans: If you write equals(Student o) instead of equals(Object o), it's METHOD OVERLOADING, not
overriding. The [Link]() is not replaced — both exist.
4.8 Coding Questions – Unit 4
Q1. Create a Product class. Override toString() to show id, name, price. Test with println.
Hint: return "Product[" + id + ", " + name + ", " + price + "]";
Q2. Create a Point class (x, y). Override equals() to return true if both x and y match.
Hint: Follow all 5 steps of proper equals() override
Q3. Override both equals() and hashCode() in a Student class. Store in a HashSet — verify no
duplicates.
Hint: [Link](name, rollNo) for hashCode()
Q4. Show difference between == and .equals() before and after overriding equals().
Hint: Create two objects with same data; test both operators
📓 Unit 5: final Keyword
5.1 Three Uses of final
Applied To Effect Example
Variable Value cannot change (constant) final int MAX = 100;
Method Cannot be overridden in subclass final void display() { }
Class Cannot be extended (no subclass) final class String { }

5.2 final Variable


class Circle {
final double PI = 3.14159; // must be initialised at declaration
// OR in constructor
void show() {
PI = 3.0; // ❌ COMPILE ERROR: cannot assign value to final
}
}

Blank final variable: declared as final but not immediately initialised. MUST be initialised in
every constructor.
class Employee {
final int EMP_ID; // blank final
Employee(int id) { this.EMP_ID = id; } // initialised in constructor
}

5.3 final Method


class Vehicle {
final void start() {
[Link]("Vehicle starting...");
}
}
class Car extends Vehicle {
@Override
void start() { } // ❌ COMPILE ERROR: cannot override final method
}

Use final methods when a specific behaviour must NOT be changed by subclasses (e.g.,
security-critical methods).

5.4 final Class


final class Utility {
static double square(double n) { return n * n; }
}
class ExtendedUtil extends Utility { } // ❌ COMPILE ERROR: cannot extend final
class
Famous final classes in Java: String, Integer, Double, System, Math — all are final.

5.5 final vs static vs static final


Modifier Meaning Example
final Value cannot change after init final int x = 10;
static Belongs to class, not instance static int count = 0;
static final Class-level constant (CONSTANT) static final double PI = 3.14;
class AppConfig {
static final String DB_URL = "jdbc:mysql://localhost/db";
static final int PORT = 3306;
}
// Access: AppConfig.DB_URL — no object needed

5.6 Viva Questions – Unit 5


[Easy] What are the 3 uses of the final keyword?
Ans: 1) final variable — constant, cannot be reassigned. 2) final method — cannot be overridden. 3) final
class — cannot be subclassed.
[Easy] Can a final variable be changed?
Ans: No. Once assigned, a final variable's value cannot be changed. Any attempt causes a compile error.
[Medium] What is a static final variable?
Ans: A class-level constant. Belongs to the class (not instance), and its value never changes. Convention:
ALL_CAPS name. E.g., static final double PI = 3.14159;
[Medium] What is a blank final variable?
Ans: A final variable declared without initialization. MUST be assigned in every constructor. Cannot be
assigned anywhere else.
[Easy] Can a final class have subclasses?
Ans: No. A final class cannot be extended. E.g., String is final — you cannot extend String.
[Easy] Can we override a final method?
Ans: No. final methods are locked — subclasses cannot override them. This is used to prevent alteration
of security-critical behaviour.
[Hard] Can a final method be overloaded?
Ans: Yes. final prevents overriding (same signature), but overloading (different parameters) is allowed.
[Hard] Is a final variable always static?
Ans: No. final and static are independent. final prevents reassignment; static makes it class-level.
Together (static final) they make a true constant.

5.7 Coding Questions – Unit 5


Q1. Create a MathConstants class with static final PI, E, GOLDEN_RATIO. Use them in area and
perimeter calculations.
Hint: Access without object: [Link]
Q2. Show all 3 final errors: try to modify final var, override final method, extend final class.
Hint: Each should produce a specific compile error with a comment
Q3. Implement a bank account with a final account number set only once in the constructor.
Hint: blank final: final int accNo; assigned only in constructor
📔 Unit 6: instanceof Operator
6.1 What is instanceof?
instanceof is a binary operator that tests whether an object is an instance of a specific class or
interface. Returns true or false.
// Syntax
objectReference instanceof ClassName

Animal a = new Dog();


[Link](a instanceof Animal); // true (Dog IS-A Animal)
[Link](a instanceof Dog); // true (actual object is Dog)
[Link](a instanceof Cat); // false (Dog is NOT Cat)

6.2 instanceof with null


Animal a = null;
[Link](a instanceof Animal); // false — null is never an instance
instanceof always returns false for null — no NullPointerException is thrown. This makes it
safe to use.

6.3 Primary Use: Safe Downcasting


Animal a = new Dog();

// Unsafe — might throw ClassCastException


Cat c = (Cat) a; // ❌ ClassCastException at runtime

// Safe — check first with instanceof


if (a instanceof Dog) {
Dog d = (Dog) a;
[Link](); // ✅ safe
}

6.4 Pattern Matching instanceof (Java 16+)


Modern Java combines instanceof check + cast in one line — cleaner code.
// Old way
if (obj instanceof String) {
String s = (String) obj;
[Link]([Link]());
}

// New way (Java 16+ Pattern Matching)


if (obj instanceof String s) { // check + bind in one step
[Link]([Link]());
}

6.5 instanceof in Hierarchy


class A { }
class B extends A { }
class C extends B { }

C obj = new C();


[Link](obj instanceof C); // true
[Link](obj instanceof B); // true (C IS-A B)
[Link](obj instanceof A); // true (C IS-A B IS-A A)

6.6 Viva Questions – Unit 6


[Easy] What is the instanceof operator?
Ans: A binary operator that returns true if an object is an instance of a given class or implements a given
interface.
[Easy] What does instanceof return for null?
Ans: Always false. null is not an instance of any class. Importantly, it does NOT throw a
NullPointerException.
[Medium] Why is instanceof used before downcasting?
Ans: To avoid ClassCastException. instanceof verifies the object's actual type before casting, making
downcasting safe.
[Medium] If Dog extends Animal, does 'new Dog() instanceof Animal' return true?
Ans: Yes. Because of IS-A: every Dog is an Animal. instanceof checks the entire inheritance hierarchy.
[Hard] What is pattern matching instanceof (Java 16+)?
Ans: A feature that combines instanceof check and type cast into one: if (obj instanceof String s) — s is
available directly inside the block.

6.7 Coding Questions – Unit 6


Q1. Create a hierarchy: Shape → Circle, Rectangle, Triangle. Store all in a Shape[]. Use instanceof to
identify type and call a type-specific method.
Hint: for each shape: if(s instanceof Circle) { (Circle)s).getRadius() }
Q2. Write a method processAnimal(Animal a) that uses instanceof to call bark() if Dog, meow() if Cat.
Hint: Downcast safely inside each instanceof block
Q3. Show instanceof with null. Verify no exception is thrown.
Hint: Animal a = null; sout(a instanceof Animal) → false
📘 Unit 7: Abstract Class and Abstract Methods
7.1 What is an Abstract Class?
An abstract class is a class that cannot be instantiated. It is designed to be extended. It may contain
abstract methods (no body) and concrete methods (with body).
Feature Detail
Keyword abstract class ClassName { }
Can be instantiated? ❌ No — new AbstractClass() causes compile error
Can have constructor? ✅ Yes — called via super() from subclass
Abstract methods Method declared without body — subclass MUST implement
Concrete methods Regular methods with body — inherited as-is
Fields Can have instance and static fields
Access modifiers Any — public, protected, private, default

7.2 Abstract Method


Declared with abstract keyword, no method body (no { }). The subclass MUST override ALL abstract
methods, or itself be declared abstract.
abstract class Shape {
String color; // concrete field

Shape(String color) { [Link] = color; } // constructor

abstract double area(); // abstract method — no body


abstract double perimeter(); // abstract method

void displayColor() { // concrete method


[Link]("Color: " + color);
}
}

7.3 Concrete Subclass


class Circle extends Shape {
double radius;

Circle(double radius, String color) {


super(color); // call abstract class constructor
[Link] = radius;
}

@Override
double area() { return [Link] * radius * radius; }

@Override
double perimeter() { return 2 * [Link] * radius; }
}

class Rectangle extends Shape {


double l, w;
Rectangle(double l, double w, String color) {
super(color); this.l=l; this.w=w;
}
@Override double area() { return l * w; }
@Override double perimeter() { return 2*(l+w); }
}

// Usage
Shape s = new Circle(5, "Red"); // Upcasting
[Link](); // concrete method
[Link]([Link]()); // 78.53...
// new Shape("Blue"); // ❌ Cannot instantiate abstract class

7.4 Abstract Class with Partial Implementation


This is the Template Method Pattern — abstract class defines the ALGORITHM SKELETON,
subclasses fill in the STEPS.
abstract class DataProcessor {
// Template method — defines the algorithm
final void process() {
readData(); // abstract — subclass provides
processData(); // abstract — subclass provides
writeData(); // concrete — common for all
}

abstract void readData();


abstract void processData();

void writeData() {
[Link]("Writing data to output...");
}
}

class CSVProcessor extends DataProcessor {


void readData() { [Link]("Reading CSV"); }
void processData() { [Link]("Processing CSV"); }
}

7.5 Abstract Class Rules Summary


Rule Details
abstract class cannot be instantiated new AbstractClass() → compile error
May have 0 abstract methods A class can be abstract even with no abstract methods
Concrete subclass must implement ALL Or itself must be declared abstract
abstract methods
abstract method cannot be private private methods cannot be overridden, making abstract +
private contradictory
Rule Details
abstract method cannot be static Static methods are not overridden (only hidden)
abstract method cannot be final final prevents overriding, but abstract requires it
Can have constructors Called via super() from child — not directly

7.6 Viva Questions – Unit 7


[Easy] What is an abstract class?
Ans: A class declared with abstract keyword that cannot be instantiated. It may contain abstract methods
(no body) and concrete methods (with body).
[Easy] What is an abstract method?
Ans: A method with abstract keyword and NO body. The subclass that extends the abstract class MUST
provide the implementation.
[Easy] Can we instantiate an abstract class?
Ans: No. new AbstractClass() causes a compile error. It must be subclassed and the subclass can be
instantiated.
[Medium] Can an abstract class have a constructor?
Ans: Yes. Though you can't call it directly (since it can't be instantiated), it is called via super() from the
child class constructor.
[Medium] Can an abstract class have no abstract methods?
Ans: Yes. A class can be abstract even if all its methods are concrete. This prevents direct instantiation
but still allows subclassing.
[Medium] What must a concrete subclass do with abstract methods?
Ans: Implement (override) ALL abstract methods from the parent. If it doesn't, it must itself be declared
abstract.
[Hard] Can abstract methods be private, static, or final?
Ans: No to all. Private — can't be overridden; static — not overridden (hidden); final — blocks overriding.
All three contradict the purpose of abstract.
[Hard] What is the Template Method Pattern?
Ans: A design pattern where an abstract class defines the algorithm skeleton in a concrete method, but
defers specific steps to abstract methods implemented by subclasses.

7.7 Coding Questions – Unit 7


Q1. Design an abstract Animal class with abstract sound() and move(). Create Dog, Bird, Fish
subclasses. Polymorphically call sound() and move().
Hint: Animal[] animals = {new Dog(), new Bird(), new Fish()}; for loop
Q2. Implement Template Method Pattern: abstract class Beverage with final prepare(). Steps: boil(),
brew() (abstract), pour(), addExtras() (abstract).
Hint: Tea and Coffee extend Beverage with their own brew() and addExtras()
Q3. Create abstract Vehicle with abstract fuelType() and engineStart(). Show how subclass MUST
implement both.
Hint: Car, Bicycle extend Vehicle; Bicycle has no fuel — return 'None'
Q4. What happens when you DON'T implement an abstract method? Show the compile error.
Hint: Leave one abstract method unimplemented and observe error message
📗 Unit 8: Interfaces
8.1 What is an Interface?
An interface is a 100% abstract contract that defines what a class MUST do, but NOT how. A class
implements an interface using the implements keyword.
Feature Interface Behaviour
Variables Implicitly public static final (constants only)
Methods (traditional) Implicitly public abstract
default methods (Java 8+) Concrete method with default keyword
static methods (Java 8+) Belongs to interface, called via [Link]()
private methods (Java 9+) Helper methods inside interface
Instantiation Cannot be instantiated directly
Multiple implementation A class can implement multiple interfaces ✅
Extends An interface can extend multiple interfaces

8.2 Interface Syntax


interface Drawable {
int MAX_SIZE = 100; // implicitly: public static final

void draw(); // implicitly: public abstract


void resize(int factor); // implicitly: public abstract
}

8.3 Implementing an Interface


class Circle implements Drawable {
double radius;
Circle(double r) { [Link] = r; }

@Override
public void draw() {
[Link]("Drawing Circle with radius " + radius);
}

@Override
public void resize(int factor) {
radius *= factor;
}
}

8.4 Multiple Interfaces (Solving Multiple Inheritance)


interface Flyable { void fly(); }
interface Swimmable{ void swim(); }
class Duck implements Flyable, Swimmable {
@Override public void fly() { [Link]("Duck flying"); }
@Override public void swim() { [Link]("Duck swimming"); }
}
A class can implement MULTIPLE interfaces — this is how Java achieves multiple
inheritance of TYPE.

8.5 Interface Extending Interface


interface Animal { void breathe(); }
interface Pet extends Animal { void play(); }

class Dog implements Pet {


public void breathe() { [Link]("Breathing"); }
public void play() { [Link]("Playing fetch"); }
}

8.6 default Methods (Java 8+)


default methods have a method body inside an interface. They provide backward-compatible new
functionality without breaking existing implementations.
interface Printable {
void print(); // abstract

default void printTwice() { // default — has body


[Link]("=== Printing Twice ===");
print();
print();
}
}

class Document implements Printable {


@Override
public void print() { [Link]("Document content"); }
// printTwice() inherited — can override if needed
}

Document d = new Document();


[Link](); // uses default implementation

Overriding a default Method


class FancyDocument implements Printable {
@Override public void print() { [Link]("Fancy!"); }

@Override
public void printTwice() { // overriding the default
[Link]("★ " );
print(); print();
[Link]("★ ");
}
}
8.7 static Methods in Interface (Java 8+)
Static interface methods belong to the interface itself. Cannot be overridden. Called via
[Link]().
interface MathOps {
static int square(int n) { return n * n; }
static int cube(int n) { return n * n * n; }
static boolean isEven(int n) { return n % 2 == 0; }
}

// Usage — called on interface, NOT on object


[Link]([Link](5)); // 25
[Link]([Link](3)); // 27
[Link]([Link](4)); // true

Interface static methods are NOT inherited by implementing classes. They must be called as
[Link](), not [Link]().

8.8 Diamond Problem with default Methods


interface A { default void show() { [Link]("A"); } }
interface B { default void show() { [Link]("B"); } }

class C implements A, B {
@Override
public void show() { // MUST override to resolve conflict
[Link](); // explicitly choose A's version
}
}
If two interfaces have the same default method, the implementing class MUST override it —
otherwise compiler error.

8.9 private Methods in Interface (Java 9+)


private interface methods are helper methods used by default or static methods inside the interface.
Not visible to implementing classes.
interface Logger {
default void logInfo(String msg) { log("INFO", msg); }
default void logError(String msg) { log("ERROR", msg); }

private void log(String level, String msg) { // helper


[Link]("[" + level + "] " + msg);
}
}

8.10 Abstract Class vs Interface – Complete Comparison


Aspect Abstract Class Interface
Keyword abstract class interface / implements
Instantiation ❌ Cannot ❌ Cannot
Methods abstract + concrete abstract + default + static + private
Aspect Abstract Class Interface
Variables Any type Only public static final
Constructor ✅ Yes ❌ No
Multiple inheritance ❌ No (single extends) ✅ Yes (multiple implements)
Access modifiers on Any public (implicit)
methods
IS-A relationship Strong (shared state) Capability / contract
Speed Slightly faster Slightly slower (historically)
Use when Sharing code + IS-A relationship Defining a contract / capability

8.11 When to Use Abstract Class vs Interface


Scenario Prefer
Strong IS-A + shared fields + some common logic Abstract Class
Unrelated classes need same capability (Flyable, Interface
Serializable)
Multiple inheritance of type needed Interface
Adding new method to all implementors (backward Interface default method
compat)
Providing constructor for initialization Abstract Class
Defining constants used across classes Interface (static final)

8.12 Viva Questions – Unit 8


[Easy] What is an interface?
Ans: A reference type that defines a contract — a set of method signatures (and optionally default/static
methods) that implementing classes must fulfil.
[Easy] What are the implicit modifiers of interface methods and variables?
Ans: Methods: public abstract. Variables: public static final. These modifiers are added automatically even
if not written.
[Easy] Can a class implement multiple interfaces?
Ans: Yes. Unlike class inheritance (single), a class can implement any number of interfaces. This
achieves multiple inheritance of type.
[Medium] What is a default method in interface?
Ans: Introduced in Java 8. A method with a body inside an interface. Allows new functionality to be added
to interfaces without breaking existing implementations.
[Medium] What is a static method in interface?
Ans: Introduced in Java 8. A utility method belonging to the interface itself. Called via
[Link](). NOT inherited by implementing classes.
[Hard] What is the Diamond Problem with interfaces?
Ans: If two interfaces define the same default method and a class implements both, ambiguity arises. The
class MUST override the method; it can call a specific version via [Link]().
[Medium] Can interface extend another interface?
Ans: Yes. An interface can extend one or multiple interfaces using the extends keyword: interface C
extends A, B { }
[Medium] What is the difference between default method and abstract method in interface?
Ans: Abstract method: no body, implementing class must override. default method: has a body,
implementing class can optionally override.
[Hard] Can an interface have private methods?
Ans: Yes, from Java 9. They are helper methods for default and static methods inside the interface. Not
visible to implementing classes.
[Medium] Can interface variables be changed by an implementing class?
Ans: No. Interface variables are public static final — constants. They cannot be reassigned.

8.13 Coding Questions – Unit 8


Q1. Define Flyable and Swimmable interfaces. Make Duck implement both. Call all methods via each
interface reference.
Hint: Flyable f = new Duck(); [Link](); Swimmable s = new Duck(); [Link]();
Q2. Add a default method getDescription() to an existing interface. Show that existing implementing
classes work without change.
Hint: Backward compatibility of default method
Q3. Create a MathUtils interface with static helper methods: square(), cube(), factorial(). Call without
object.
Hint: [Link](5)
Q4. Demonstrate the Diamond Problem: two interfaces with same default method. Resolve in
implementing class using [Link]().
Hint: Interface A, B both have default void show(); class C implements A, B must override
Q5. Design a Payment interface with pay(double amount). Implement with CreditCard, UPI, Crypto
classes. Process payments polymorphically.
Hint: Payment p; p = new UPI(); [Link](500.0);
Q6. Create a Sortable interface with static compare() helper and default sort() using it. Implement in a
StudentList class.
Hint: Show how static and default methods work together
⚡ Quick Reference Cheat Sheet
Inheritance Rules at a Glance
• extends for class inheritance, implements for interfaces
• Single class inheritance only; multiple interface implementation allowed
• private members: not inherited; constructors: not inherited
• super() in first line of child constructor calls parent constructor

Method Overriding Rules


• Same name + same return type + same parameters
• Cannot be more restrictive in access; can be broader
• Cannot override final, static, or private methods
• @Override annotation strongly recommended

final, super, instanceof Summary


Keyword Applied to Effect
final Variable Cannot reassign
final Method Cannot override
final Class Cannot extend
super Field Access parent's version
super Method Call parent's version
super() Constructor Call parent's constructor (must be first)
instanceof Object, Class Returns boolean; false for null

Abstract Class vs Interface Quick Guide


Need Choose
Shared code + state + IS-A Abstract Class
Pure contract / capability Interface
Multiple inheritance of type Interface
Constructor logic needed Abstract Class
Add method without breaking old code Interface default method
Utility/helper methods Interface static method

Interface Method Types (Java 8/9+)


Type Keyword Inherited? Overridable? Called Via
Abstract (none) Yes Yes (required) [Link]()
Default default Yes Yes (optional) [Link]()
Static static No No [Link]()
Type Keyword Inherited? Overridable? Called Via
Private private No No Only inside interface

Common Mistakes to Avoid


• Using == to compare objects instead of .equals() — compares references!
• Forgetting to override ALL abstract methods → compile error
• Trying to instantiate abstract class or interface → compile error
• Trying to reassign interface variables (they are final constants)
• Not resolving Diamond Problem when two interfaces have same default method
• Using super() after another statement in constructor → compile error
• Calling interface static method via object → use [Link]() instead

Code every day. Every bug you fix is a concept you own. You've got this! 🚀

You might also like