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

Basic

The document provides an overview of key Java concepts including the Java Virtual Machine (JVM), its components, and its role in executing Java bytecode, along with comparisons of JDK, JRE, and JVM. It also explains object-oriented programming principles such as inheritance, encapsulation, polymorphism, and access modifiers, detailing their purposes and implementations in Java. Additionally, it covers the significance of constructors and their types, emphasizing their role in object initialization.

Uploaded by

arpit panda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

Basic

The document provides an overview of key Java concepts including the Java Virtual Machine (JVM), its components, and its role in executing Java bytecode, along with comparisons of JDK, JRE, and JVM. It also explains object-oriented programming principles such as inheritance, encapsulation, polymorphism, and access modifiers, detailing their purposes and implementations in Java. Additionally, it covers the significance of constructors and their types, emphasizing their role in object initialization.

Uploaded by

arpit panda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

✅ [Link] is Java Virtual Machine (JVM)?

“The Java Virtual Machine (JVM) is a part of the Java Runtime Environment that is responsible for
executing Java bytecode. It provides a runtime environment that abstracts the underlying
operating system and hardware, making Java platform-independent.”

🔁 How It Works
1. Java code ( .java ) is compiled by the Java compiler ( javac ) into bytecode ( .class files).

2. This bytecode is not specific to any machine.


3. The JVM loads and executes the bytecode on any system that has a compatible JVM installed.

🧱 Key Responsibilities of JVM


Function Description

Class Loading Loads .class files into memory

Bytecode Verification Ensures code follows JVM rules and is secure

Execution Uses an interpreter or JIT compiler to run bytecode

Memory Management Allocates and deallocates memory for objects

Garbage Collection Automatically frees memory used by unreferenced objects

Exception Handling Manages runtime errors

🧠 Main Components of JVM


1. Class Loader – Loads class files when needed.

2. Runtime Memory Areas:

Heap – Stores objects (shared across threads)

Stack – Stores method calls and local variables (per thread)

© 2025 CloudTech. All rights reserved.


Method Area – Stores class metadata and static variables
Program Counter (PC) – Tracks current instruction per thread

Native Method Stack – Executes native (non-Java) methods

3. Execution Engine:

Interpreter – Reads bytecode line by line

JIT Compiler – Converts bytecode to native code for performance

4. Garbage Collector – Cleans up unused memory automatically

🔄 JVM = Write Once, Run Anywhere


The JVM enables the “Write Once, Run Anywhere” philosophy of Java, meaning the same compiled code can

run on any operating system that has a JVM.

📝 Sample Interview Answer:


"The JVM is a virtual machine that executes Java bytecode. It’s part of the Java platform and is
responsible for class loading, bytecode verification, memory management, garbage collection, and
interpreting or compiling code for execution. The JVM makes Java platform-independent,

allowing the same program to run on different operating systems as long as a JVM is available."

✅ [Link] is the difference between JDK, JRE, and JVM?


JVM vs JRE vs JDK – Comparison Table
Component Stands For Purpose Contains

JVM Java Virtual Machine Runs Java bytecode Execution engine only

JRE Java Runtime Provides environment to run JVM + libraries + other files
Environment Java programs

JDK Java Development Kit Provides tools to develop Java JRE + development tools ( javac ,
applications debugger, etc.)

© 2025 CloudTech. All rights reserved.


🔍 1. JVM (Java Virtual Machine)
“JVM is the engine that actually runs Java bytecode.”

Part of both JRE and JDK.

Converts bytecode into machine code.


Handles memory management, garbage collection, and thread management.
Platform-specific implementation (Windows, Linux, Mac).

🔍 2. JRE (Java Runtime Environment)


“JRE is the package needed to run Java applications.”

Contains:

JVM
Core Java libraries
Other runtime resources

Does not include tools for developing Java programs.

Used by end users who just want to run Java apps.

🔍 3. JDK (Java Development Kit)


“JDK is the full toolkit required to develop, compile, and run Java programs.”

Contains:

JRE
Compiler ( javac )

Debugger
Javadoc

Other development tools

Used by developers to write and compile Java code.


© 2025 CloudTech. All rights reserved.
📝 Sample Interview Answer:
"The JVM is the engine that runs Java bytecode. The JRE includes the JVM and libraries required

to run Java applications. The JDK includes both the JRE and development tools like the compiler
and debugger, which are needed to write and build Java applications."

✅ [Link] is Inheritance in Java?


“Inheritance is an object-oriented programming concept in Java where one class acquires the
properties and behaviors (fields and methods) of another class. It promotes code reusability and

supports hierarchical classification.”

🧠 Why Use Inheritance?


Reusability – Avoid writing the same code again.

Extensibility – Add or override functionality in child classes.

Polymorphism – Enable dynamic method dispatch (runtime behavior).

🧾 Syntax in Java
class Parent {

void display() {

[Link]("Parent display");
}

class Child extends Parent {

void show() {

[Link]("Child show");
}

Usage:
© 2025 CloudTech. All rights reserved.
Child obj = new Child();
[Link](); // Inherited from Parent

[Link](); // Defined in Child

📦 Types of Inheritance in Java


Supported in
Type Java Example

Single Inheritance ✅ Yes One child extends one parent

Multilevel Inheritance ✅ Yes Class C extends B, which extends A

Hierarchical Inheritance ✅ Yes Multiple classes extend a single parent

Multiple Inheritance (with ❌ No Java doesn’t support this directly (to avoid
classes) ambiguity)

Multiple Inheritance (with ✅ Yes Supported via interfaces


interfaces)

📝 Sample Interview Answer:


“Inheritance in Java allows one class to inherit fields and methods from another class using the
extends keyword. It’s used for code reuse and to implement polymorphism. For example, if a Car

class inherits from a Vehicle class, it automatically gets access to the common vehicle behaviors,

and it can also override or extend them.”

✅ [Link] is Encapsulation in Java?


“Encapsulation is the concept of wrapping data (variables) and code (methods) together as a single

unit, and restricting direct access to some of the object’s components. It’s used to protect the

internal state of an object from unintended interference.”

🎯 Purpose of Encapsulation

© 2025 CloudTech. All rights reserved.


Data hiding – Internal details are hidden from the outside world.
Improved security – Only allowed methods can access or modify the data.

Modularity – You can change internal implementation without affecting external code.

🛠️ How is Encapsulation Achieved in Java?


1. Declare fields as private – So they can’t be accessed directly.

2. Provide public getter and setter methods – To read and modify the values safely.

🧾 Example
public class Employee {

private String name; // private field

// Public getter

public String getName() {

return name;
}

// Public setter

public void setName(String newName) {


[Link] = newName;
}

Usage:

Employee emp = new Employee();


[Link]("Alice");

[Link]([Link]()); // Output: Alice

📌 Key Points
© 2025 CloudTech. All rights reserved.
You control how data is accessed or modified.
You can add validation inside setters.
It’s a core pillar of OOP in Java (along with inheritance, abstraction, and polymorphism).

📝 Sample Interview Answer:


“Encapsulation in Java means binding data and methods that operate on that data into a single

unit and restricting direct access to some of the object’s fields. It is achieved by making fields
private and exposing them through public getters and setters. This helps protect the internal

state of an object and promotes better control and maintainability.”

✅ [Link] is Polymorphism in Java?


“Polymorphism is an object-oriented principle in Java that allows one interface to be used for
different underlying data types or implementations. In simple terms, it means the same method

name can behave differently depending on the object that invokes it.”

🧠 Types of Polymorphism in Java


Type Description Achieved By

Compile-time (Static) Method is chosen at compile time Method overloading

Runtime (Dynamic) Method is chosen at runtime Method overriding

🔹 1. Compile-time Polymorphism (Method Overloading)


Same method name, different parameter list, same class

class Calculator {
int add(int a, int b) {

return a + b;
}

double add(double a, double b) {


© 2025 CloudTech. All rights reserved.
return a + b;
}
}

The method to call is decided at compile time.


Improves readability and flexibility.

🔹 2. Runtime Polymorphism (Method Overriding)


Same method signature, subclass provides a different implementation

class Animal {
void sound() {

[Link]("Animal makes a sound");


}
}

class Dog extends Animal {


void sound() {

[Link]("Dog barks");
}
}

Usage:

Animal obj = new Dog(); // Reference of parent, object of child


[Link](); // Output: Dog barks

The method to call is decided at runtime based on the object.


Enables dynamic method dispatch.

📝 Sample Interview Answer:

© 2025 CloudTech. All rights reserved.


“Polymorphism in Java allows a single method or interface to operate in different ways based on

the context. It comes in two forms: compile-time polymorphism using method overloading, and
runtime polymorphism using method overriding. This enables flexibility and extensibility in
object-oriented programming.”

✅ [Link] is the difference between Method Overloading vs


Method Overriding
Feature Method Overloading Method Overriding

Definition Defining multiple methods with the Redefining a method in a child class that is
same name but different parameter already defined in the parent class, with the
lists within the same class. same method signature.

Time Compile-time polymorphism Runtime polymorphism

Method Method name must be the same, but the Method name, return type, and parameters
Signature number or type of parameters must must be exactly the same.
differ.

Return Type Can differ (though it’s not common Must be the same as the parent method (same
practice to overload methods only by signature).
return type).

Binding Resolved at compile time. Resolved at runtime (dynamic method


dispatch).

Inheritance No inheritance required (methods are in Must involve inheritance, where the child class
the same class). overrides the parent class method.

Use Case Used when you want the same method to Used when you want to provide a specific
handle different types or numbers of implementation of a method in a subclass.
inputs.

Example Method name is the same, but the Method in child class provides a new definition
parameters differ (e.g., add(int, int) for an inherited method from the parent class.
and add(double, double) ).

🧾 Examples
Method Overloading

© 2025 CloudTech. All rights reserved.


class Calculator {
// Overloaded method with two int parameters

int add(int a, int b) {


return a + b;
}

// Overloaded method with two double parameters


double add(double a, double b) {

return a + b;
}
}

Here, both add methods have the same name but different parameter types. This is an example of

compile-time polymorphism.

Method Overriding
class Animal {

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

class Dog extends Animal {

@Override
void sound() {
[Link]("Dog barks");

}
}

Here, Dog class overrides the sound method from the Animal class. This is an example of runtime

polymorphism, where the actual method that is called depends on the object type ( Dog in this case).

📝 Sample Interview Answer:


© 2025 CloudTech. All rights reserved.
“Method overloading occurs when multiple methods with the same name exist in the same class,
but with different parameters. It’s a form of compile-time polymorphism. Method overriding

happens when a subclass provides a specific implementation of a method already defined in the
parent class, with the same method signature. Overriding is resolved at runtime and is a key
feature of runtime polymorphism.”

✅ [Link] are Access Modifiers in Java?


“Access modifiers in Java are keywords that determine the visibility or accessibility of classes,
methods, constructors, and variables. They control where a class member can be accessed from,

i.e., whether it can be accessed within the same class, package, or from other classes.”

🧱 Types of Access Modifiers in Java


1. public

2. protected

3. default (no modifier)

4. private

📜 1. public Access Modifier

Scope: Accessible from anywhere (within the same class, different class, same package, and different
package).
Usage: When you want to make a class or class member accessible from any other class or package.

public class MyClass {


public int data;

Example: public methods or classes can be accessed across different packages.

📜 2. protected Access Modifier


© 2025 CloudTech. All rights reserved.
Scope: Accessible within the same package and subclasses (even if they are in different packages).
Usage: When you want to restrict access to members within the same package but still allow subclasses to

access them.

class Animal {
protected void makeSound() {

[Link]("Sound");
}

class Dog extends Animal {

void display() {

makeSound(); // Accessible because Dog is a subclass of Animal


}

Example: A protected method in a parent class can be accessed by subclasses (even if they are in

different packages).

📜 3. Default (Package-Private) Access Modifier


Scope: Accessible only within the same package.

Usage: When no access modifier is specified. The default access level is package-private, meaning it is

accessible only within the same package.

class MyClass {

int data; // Default (package-private)


}

Example: default members are not accessible outside the package, even in subclasses.

📜 4. private Access Modifier

Scope: Accessible only within the same class.

© 2025 CloudTech. All rights reserved.


Usage: When you want to restrict access to members of a class so that they cannot be accessed from
outside the class.

class MyClass {
private int data;

private void show() {


[Link]("Private method");

Example: A private method or variable can only be accessed inside the class where it is declared.

🔀 Summary of Scopes
Access Modifier Same Class Same Package Subclass Different Package

public Yes Yes Yes Yes

protected Yes Yes Yes Yes (only through subclass)

default Yes Yes No No

private Yes No No No

📝 Sample Interview Answer:


“In Java, there are four main access modifiers: public , protected , default (package-private), and

private . public allows access from anywhere, protected allows access within the same package

and by subclasses, default (no modifier) allows access within the same package only, and private

restricts access to within the same class.”

✅ [Link] is a Constructor in Java?


“A constructor in Java is a special method that is automatically called when an object of a class is
created. It is used to initialize the object’s state (i.e., assign values to fields or perform setup

© 2025 CloudTech. All rights reserved.


operations).”

🧠 Key Points About Constructors


Name: Must have the same name as the class.
No return type: Constructors do not have a return type, not even void .

Automatic Call: The constructor is called automatically when an object is instantiated using the new

keyword.

Purpose: Primarily used to initialize the object’s instance variables when an object is created.

🧾 Types of Constructors in Java


1. Default Constructor

2. Parameterized Constructor

🔹 1. Default Constructor
Definition: A constructor with no parameters. If no constructor is explicitly defined, Java provides a
default constructor that initializes the object with default values (like null , 0 , false ).

Usage: Used when no special initialization is required at the time of object creation.

class Car {
String model;

int year;

// Default constructor

public Car() {

model = "Unknown";
year = 2023;

When you create an object:

© 2025 CloudTech. All rights reserved.


Car car1 = new Car(); // Calls default constructor
[Link]([Link]); // Output: Unknown

🔹 2. Parameterized Constructor
Definition: A constructor that takes parameters to initialize an object with specific values when it is
created.

Usage: Used when you want to initialize an object with specific values at the time of creation.

class Car {

String model;

int year;

// Parameterized constructor

public Car(String model, int year) {


[Link] = model;

[Link] = year;

}
}

When you create an object:

Car car1 = new Car("Tesla", 2022); // Calls parameterized constructor

[Link]([Link]); // Output: Tesla

🧾 Constructor Overloading
“Java allows constructor overloading, which means you can have multiple constructors with the
same name but different parameter lists in a class.”

class Car {
String model;

© 2025 CloudTech. All rights reserved.


int year;

// Default constructor

public Car() {

model = "Unknown";
year = 2023;

// Parameterized constructor

public Car(String model, int year) {

[Link] = model;
[Link] = year;

You can create an object using either constructor:

Car car1 = new Car(); // Default constructor


Car car2 = new Car("BMW", 2021); // Parameterized constructor

📝 Sample Interview Answer:


“A constructor in Java is a special method used to initialize objects. It has the same name as the
class and no return type. There are two main types of constructors: default constructors (with no

parameters) and parameterized constructors (which allow passing values at the time of object

creation). Constructors can also be overloaded to provide multiple ways of initializing objects.”

✅ [Link] is the Difference Between == and equals() in Java?


“In Java, == and equals() are both used for comparison, but they work in different ways. ==

compares object references (memory addresses), while equals() compares the actual content or

values of objects.”

© 2025 CloudTech. All rights reserved.


🧠 Key Differences Between == and equals()
Feature == (Reference Comparison) equals() (Content Comparison)

Comparison Compares memory references Compares actual values (content or state) of the
Type (addresses). objects.

Works With Primitive types and object Objects (particularly for comparing content).
references.

Default For objects, == checks if both The default equals() method (in Object class)
Behavior references point to the same object checks for reference equality, but can be overridden
in memory. to compare object content.

Overriding Cannot be overridden (as it is a part Can be overridden to compare custom objects based
of the primitive comparison). on their content.

🧾 Examples
Using == (Reference Comparison)
String str1 = new String("Java");
String str2 = new String("Java");

[Link](str1 == str2); // Output: false (compares memory addresses)

str1 and str2 are two different objects in memory, even though they contain the same value.

Using equals() (Content Comparison)


String str1 = new String("Java");
String str2 = new String("Java");

[Link]([Link](str2)); // Output: true (compares actual content)

equals() compares the actual content of the objects, and in this case, the content of str1 and str2

is the same.

© 2025 CloudTech. All rights reserved.


🔑 Key Points to Remember
== :

For primitive types, it compares the value (e.g., int , float ).

For objects, it compares whether two references point to the same object in memory.

equals() :

Used for object comparison to check if two objects are logically equivalent (i.e., their

content is the same).

Can be overridden in classes to customize the comparison logic. For example, in the String

class, equals() compares the actual value of the strings.

📝 Sample Interview Answer:


" == is used for reference comparison, meaning it checks if two references point to the same

memory location. It works with both primitive types and object references. On the other hand,

equals() is used for content comparison, specifically to check if two objects have the same values.

In most classes, equals() should be overridden to perform content comparison, such as in the

String class."

✅ [Link] is the static Keyword in Java?


“The static keyword in Java is used to declare class-level variables, methods, blocks, or nested

classes that belong to the class itself rather than to any specific object of the class.”

🧠 Uses of the static Keyword in Java

1. Static Variables (Class Variables):

Definition: A variable declared as static is shared by all instances of the class, rather than

having a separate copy for each object.

© 2025 CloudTech. All rights reserved.


Usage: When you need a variable to be common to all instances of a class (e.g., a constant or a

counter).

Example:

class Counter {

static int count = 0; // Static variable

void increment() {

count++; // Incrementing the static variable

}
}

public class Main {


public static void main(String[] args) {

Counter c1 = new Counter();

Counter c2 = new Counter();


[Link]();

[Link]();

[Link]([Link]); // Output: 2
}

Explanation: Both c1 and c2 share the same count variable, and it reflects the total

changes made across all objects.

2. Static Methods:

Definition: A method declared as static can be called without creating an instance of the

class. Static methods can only access other static members (variables, methods) of the class.

Usage: When you want a method to be common to all instances of the class or when you don’t
need to access any instance-specific data.

Example:

class MathUtility {
static int add(int a, int b) {

© 2025 CloudTech. All rights reserved.


return a + b;
}

public class Main {

public static void main(String[] args) {

int result = [Link](5, 3); // Directly calling the static method


[Link](result); // Output: 8

Explanation: You can call add() without creating an instance of MathUtility .

3. Static Blocks:

Definition: A static block is used for initialization that should only be done once, when the

class is first loaded into memory.


Usage: Typically used to initialize static variables or perform complex one-time setup tasks.

Example:

class Database {

static {
[Link]("Connecting to database...");

// Perform one-time setup or connection logic

}
}

public class Main {


public static void main(String[] args) {

new Database(); // Static block will run once when the class is loaded

}
}

Explanation: The static block runs once when the Database class is loaded into memory,

before any instance of the class is created.


© 2025 CloudTech. All rights reserved.
4. Static Classes:

Definition: A static class is a nested class that does not require an instance of the outer class

to be created.

Usage: When you want to define a nested class that doesn’t depend on the outer class’s instance
variables or methods.

Example:

class Outer {

static class Inner {


void display() {

[Link]("Inside static nested class");

}
}

public class Main {

public static void main(String[] args) {

[Link] obj = new [Link]();


[Link](); // Output: Inside static nested class

Explanation: You can create an instance of Inner without needing an instance of Outer .

🔑 Key Points About the static Keyword

Shared across all instances: Static variables and methods are shared by all instances of a class.

Accessed without creating objects: You can access static members without creating an instance of the

class.
Limited access in static methods: Static methods can only directly access other static members of the

class. They cannot access instance variables or instance methods.

Used for constants: Static variables are often used for constants (i.e., values that should not change and
are shared by all instances).

© 2025 CloudTech. All rights reserved.


📝 Sample Interview Answer:
“The static keyword in Java is used to define class-level members (variables, methods, or blocks)

that belong to the class rather than to individual objects. Static members are shared across all

instances of the class. A static variable or method can be accessed directly using the class name,
and they are typically used for values that are common to all instances or for one-time setup in

static blocks.”

✅ [Link] Between static and non-static Methods in


Java
Feature Static Methods Non-static Methods

Keyword Declared with the static keyword. Not declared with static .

Association Belongs to the class, not to any instance of Belongs to instances of the class
the class. (objects).

Accessing Can be called without creating an object Can only be called with an instance
of the class. of the class.

Access to Instance Cannot directly access non-static instance Can access both static and non-
Variables variables or methods. static variables and methods.

Memory Location Static methods are stored in the method Non-static methods are stored in the
area (class level). heap (object level).

Use Case Used for general operations or actions that Used for operations that depend on
don’t depend on object state. the state of an object (instance).

Inheritance Can be inherited by subclasses but cannot be Can be inherited and overridden in
overridden (they are hidden if redefined). subclasses.

🧾 Examples
Static Method
class Calculator {

static int add(int a, int b) {

© 2025 CloudTech. All rights reserved.


return a + b; // Static method

}
}

public class Main {


public static void main(String[] args) {

int result = [Link](5, 3); // Calling static method without an object

[Link](result); // Output: 8
}
}

Explanation: add() is a static method. It can be called using the class name Calculator without

creating an instance of Calculator .

Non-static Method
class Calculator {

int multiply(int a, int b) {

return a * b; // Non-static method


}

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator(); // Creating an object


int result = [Link](5, 3); // Calling non-static method using the object

[Link](result); // Output: 15

Explanation: multiply() is a non-static method. It can only be called on an instance of Calculator

(i.e., an object).

🔑 Key Differences
© 2025 CloudTech. All rights reserved.
Static Methods:

Can be called without creating an instance of the class.

Cannot access instance variables or instance methods directly (they must access only static

members of the class).

Are associated with the class itself.

Non-static Methods:

Must be called on an object (instance) of the class.

Can access both static and non-static variables and methods.

Are associated with instances of the class.

📝 Sample Interview Answer:


“In Java, static methods belong to the class itself and can be called without creating an instance of

the class. They can only directly access static members of the class. Non-static methods, on the

other hand, belong to instances of the class and can be called only through objects. Non-static

methods can access both static and non-static members of the class.”

✅ [Link] is an Abstract Class in Java?


“An abstract class in Java is a class that cannot be instantiated on its own. It is used as a blueprint

for other classes. Abstract classes can have both abstract methods (without implementation) and

concrete methods (with implementation). The purpose of an abstract class is to provide a common
base for other classes while allowing specific implementation details to be defined in the

subclasses.”

🧠 Key Features of an Abstract Class


1. Cannot be Instantiated:

You cannot create an object of an abstract class directly.

© 2025 CloudTech. All rights reserved.


It must be inherited by a concrete class (non-abstract) that provides implementations for any

abstract methods.

2. Abstract Methods:

An abstract method is a method that is declared without an implementation (no body).

Subclasses of the abstract class are required to implement these abstract methods unless they

are also abstract.

3. Concrete Methods:

An abstract class can also have methods that are fully implemented (i.e., concrete methods).

These methods can be directly used by subclasses.

4. Constructors:

Abstract classes can have constructors, but they cannot be directly called to create an object.

Instead, they are used by concrete subclasses.

5. Fields:

Abstract classes can have instance variables and constants, just like regular classes.

6. Inheritance:

A concrete class that extends an abstract class must implement all the abstract methods of the

abstract class (unless the subclass is also abstract).

🧾 Example of an Abstract Class


abstract class Animal {

// Abstract method (no implementation)

abstract void sound();

// Concrete method

void sleep() {

[Link]("The animal is sleeping.");

© 2025 CloudTech. All rights reserved.


class Dog extends Animal {

// Implementing the abstract method

void sound() {

[Link]("The dog barks.");

public class Main {

public static void main(String[] args) {

Dog dog = new Dog();

[Link](); // Output: The dog barks.

[Link](); // Output: The animal is sleeping.


}

Explanation:

The Animal class is abstract, with one abstract method ( sound() ) and one concrete method

( sleep() ).

The Dog class extends Animal and provides an implementation for the sound() method.

🔑 Key Points to Remember


Abstract Methods: Methods declared without implementation. They must be implemented by concrete

subclasses.
Concrete Methods: Fully implemented methods in the abstract class that can be inherited by

subclasses.

Abstract Class Cannot Be Instantiated: You cannot create an object of an abstract class directly. It

must be subclassed.

Purpose: Abstract classes are used when you want to define common functionality for subclasses but

leave some details for subclasses to implement.

© 2025 CloudTech. All rights reserved.


📝 Sample Interview Answer:
“An abstract class in Java is a class that cannot be instantiated on its own and is meant to be

subclassed. It can contain both abstract methods (without implementation) and concrete methods

(with implementation). Abstract methods must be implemented by concrete subclasses. Abstract

classes provide a common base and can contain instance variables, constructors, and methods that
are shared by subclasses.”

✅ [Link] is an Interface in Java?


“An interface in Java is a reference type, similar to a class, but it can contain only abstract

methods, default methods, static methods, and constants (variables). Interfaces cannot have

instance variables or constructors. They are used to represent a contract or a set of methods that a

class must implement, ensuring that the class adheres to a particular behavior or specification.”

🧠 Key Features of an Interface


1. Abstract Methods:

By default, all methods in an interface are abstract (prior to Java 8). These methods have no

implementation and must be implemented by any class that implements the interface.

2. Constants:

All variables declared in an interface are public , static , and final by default. They are

treated as constants, and their values cannot be changed.

3. Multiple Inheritance:

Java allows a class to implement multiple interfaces, solving the problem of multiple

inheritance (which is not supported directly with classes).

4. Default Methods:

From Java 8 onwards, interfaces can have default methods that provide a default
implementation. These methods can be overridden by implementing classes but are optional to

© 2025 CloudTech. All rights reserved.


override.

5. Static Methods:

Java 8 also introduced static methods in interfaces. These methods can be called on the interface

itself, not on the instances of the implementing class.

6. No Constructor:

Interfaces cannot have constructors because they cannot be instantiated directly.

7. Implemented by Classes:

A class that implements an interface must provide the implementation for all of its abstract

methods unless the class is abstract.

🧾 Example of an Interface
interface Animal {

// Abstract method (no implementation)

void sound();

// Default method (with implementation)


default void sleep() {

[Link]("The animal is sleeping.");

class Dog implements Animal {

// Implementing the abstract method

public void sound() {

[Link]("The dog barks.");

public class Main {

public static void main(String[] args) {

© 2025 CloudTech. All rights reserved.


Dog dog = new Dog();

[Link](); // Output: The dog barks.

[Link](); // Output: The animal is sleeping.

Explanation:

The Animal interface has one abstract method ( sound() ) and one default method ( sleep() ).

The Dog class implements the Animal interface and provides the implementation for the

sound() method.

🔑 Key Points to Remember


Interfaces Define a Contract: An interface defines a set of methods (without implementation) that a

class must implement. It specifies what actions the implementing class should perform, but not how.

No Constructors: Interfaces cannot have constructors because they are not meant to be instantiated

directly.
Default Methods: With Java 8 and above, interfaces can have default methods with an implementation.

This allows interfaces to evolve without breaking existing code.

Multiple Inheritance: A class can implement multiple interfaces, overcoming the limitations of single

inheritance with classes.

📝 Sample Interview Answer:


“An interface in Java is a blueprint for a class that defines a contract for the methods a class must

implement. Interfaces can contain abstract methods, constants, default methods, and static

methods. A class that implements an interface must provide implementations for all its abstract

methods. Interfaces enable multiple inheritance in Java, which allows a class to implement more

than one interface.”

✅ [Link] to Implement an Interface in Java?

© 2025 CloudTech. All rights reserved.


“To implement an interface in Java, a class uses the implements keyword, followed by the name of

the interface. The class is then required to provide implementations for all the abstract methods

declared in the interface (unless the class is abstract). An interface provides a contract, and the

implementing class provides the actual behavior.”

🧠 Steps to Implement an Interface in Java


1. Define an Interface:

An interface can contain abstract methods (methods without body), default methods (with

implementation), and constants (static variables).


Abstract methods are like a blueprint that the implementing class must define.

2. Use the implements Keyword:

A class that implements an interface uses the implements keyword, followed by the interface

name.

3. Implement All Abstract Methods:

The implementing class must provide concrete implementations for all abstract methods defined

in the interface.
If the class is not abstract, it must provide implementations for all abstract methods. Otherwise,

you must declare the class as abstract .

4. Use of default Methods:

If the interface has default methods, the implementing class can either override them or use

them as they are.

🧾 Example of Implementing an Interface


// Defining an interface

interface Animal {

// Abstract method (without implementation)

void sound();

© 2025 CloudTech. All rights reserved.


// Default method (with implementation)
default void sleep() {

[Link]("The animal is sleeping.");

// Implementing the interface in a class


class Dog implements Animal {

// Providing implementation for the abstract method

public void sound() {

[Link]("The dog barks.");

}
}

public class Main {

public static void main(String[] args) {

Dog dog = new Dog();

[Link](); // Output: The dog barks.


[Link](); // Output: The animal is sleeping.

Explanation:

The Animal interface defines an abstract method sound() and a default method sleep() .

The Dog class implements the Animal interface and provides an implementation for the

sound() method. The sleep() method is inherited as-is from the interface.

🔑 Key Points to Remember


1. implements Keyword:

Use the implements keyword to tell the class to implement an interface.

© 2025 CloudTech. All rights reserved.


2. Must Implement All Abstract Methods:

The implementing class must provide concrete implementations for all abstract methods declared

in the interface. If the class does not, it must be declared as abstract .

3. Default Methods:

If the interface contains default methods, the implementing class has the option to override them.

If it doesn’t, the default implementation from the interface will be used.

4. Multiple Interfaces:

A class can implement multiple interfaces, which allows for multiple inheritance (a class can

inherit behavior from more than one interface).

📝 Sample Interview Answer:


“To implement an interface in Java, a class uses the implements keyword followed by the interface

name. The class must then provide concrete implementations for all the abstract methods defined

in the interface. If the interface contains default methods, the class can choose to override them or

use the default behavior. A class can implement multiple interfaces, allowing it to inherit
behaviors from more than one source.”

✅ [Link] is the Difference Between an Abstract Class and an


Interface
Feature Abstract Class Interface

Keyword Declared with the abstract Declared with the interface keyword.
keyword.

Methods Can have both abstract methods Can have abstract methods (without
(without implementation) and implementation), default methods (with
concrete methods (with implementation), and static methods.
implementation).

© 2025 CloudTech. All rights reserved.


Feature Abstract Class Interface

Implementation A subclass must implement abstract A class must implement all abstract
methods (if any), but it can inherit methods from the interface. If the interface
both abstract and concrete methods. has default methods, the class can use them
or override them.

Constructors Can have constructors. Cannot have constructors.

State (Instance Can have instance variables (fields) All variables in an interface are implicitly
Variables) that are non-static and non-final. public, static, and final (constants).

Access Modifiers Methods and variables can have All methods are implicitly public , and
various access modifiers like variables are public , static , and final
public , private , protected , or by default.
default .

Multiple A class can inherit from only one A class can implement multiple interfaces,
Inheritance abstract class (single inheritance). allowing multiple inheritance of behavior.

Use Case Used when you want to share Used when you want to represent a contract
common code (implementation) or a set of behaviors that can be
among classes. implemented by different classes.

Method Visibility Can have methods with different Methods are public by default.
access levels ( public , private ,
etc.).

Inheritance vs. A class extends an abstract class. A class implements an interface.


Implementation

🧠 Detailed Differences in JDK 8


1. Methods in Interfaces (JDK 8 Onwards):

In JDK 8, interfaces can now have default methods (with implementation) and static
methods.

Default methods allow interfaces to provide default behavior, meaning classes that

implement the interface don’t necessarily need to implement the method (but can override it if

needed).

Static methods in an interface can be called using the interface name, but they are not inherited

by implementing classes.

© 2025 CloudTech. All rights reserved.


Example:

interface Animal {
void sound(); // Abstract method

default void sleep() { // Default method

[Link]("The animal is sleeping.");

static void breath() { // Static method

[Link]("The animal is breathing.");

2. Abstract Methods:

Abstract classes can have both abstract and non-abstract (concrete) methods.

Interfaces (prior to JDK 8) could only have abstract methods, but now they can have default

and static methods as well.

3. State (Variables):

In abstract classes, you can have non-final, non-static instance variables.

In interfaces, variables are always public, static, and final (constants).

4. Multiple Inheritance:

Abstract classes support single inheritance. A class can only inherit from one abstract class.

Interfaces support multiple inheritance. A class can implement multiple interfaces, which

allows it to inherit behavior from more than one source.

🧾 Example to Highlight Differences


Abstract Class Example
abstract class Animal {

// Abstract method

© 2025 CloudTech. All rights reserved.


abstract void sound();

// Concrete method

void sleep() {

[Link]("The animal is sleeping.");

class Dog extends Animal {

// Implementing abstract method

void sound() {

[Link]("The dog barks.");

}
}

Explanation:

Animal is an abstract class with one abstract method ( sound() ) and one concrete method

( sleep() ).

The Dog class extends Animal and provides an implementation for sound() .

Interface Example (JDK 8+)


interface Animal {

// Abstract method

void sound();

// Default method

default void sleep() {

[Link]("The animal is sleeping.");

// Static method

static void breath() {

[Link]("The animal is breathing.");

© 2025 CloudTech. All rights reserved.


}

class Dog implements Animal {

// Implementing the abstract method

public void sound() {

[Link]("The dog barks.");

}
}

Explanation:

Animal is an interface with an abstract method ( sound() ), a default method ( sleep() ), and a

static method ( breath() ).

The Dog class implements the Animal interface and provides an implementation for sound() .

📝 Sample Interview Answer:


“In Java, both abstract classes and interfaces are used to define methods that must be
implemented by other classes, but they have key differences. An abstract class can have both

abstract and concrete methods, instance variables, and constructors, while an interface can only

have abstract methods (until Java 8 introduced default and static methods). A class can implement

multiple interfaces but can inherit from only one abstract class. Abstract classes are used when

you want to share code among related classes, while interfaces are used to define a contract that

multiple classes can follow, often supporting multiple inheritance.”

© 2025 CloudTech. All rights reserved.

You might also like