Guide To Clear Java Developer Interview Free Sample

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Table of Contents

Introduction .......................................................................................................................... 3
How to Prepare for a Java Developer Interview ..................................................... 4
How to introduce yourself ............................................................................................... 6
Tell me about yourself, tell me about skills? ....................................................... 6
Tell me about your project & architecture please explain it? Draw the
architecture, framework and technology used?.................................................. 6
Best practices to follow while developing an application? .............................. 7
What challenging things you have done it of spring and hibernate and
database?........................................................................................................................... 8
Explain the code and flow of the project in and out of it? .............................. 8
How do you build your code, how to do packaging? ........................................ 9
Object Oriented Programming ..................................................................................... 11
Tell me about OOPS concept in java? ................................................................... 11
Four principle of OOP? Abstraction, encapsulation, inheritance
polymorphism? .............................................................................................................. 11
Inheritance vs composition? ..................................................................................... 11
Abstraction vs polymorphism? ................................................................................ 12
Abstract class vs interface? ...................................................................................... 12
Abstract class with constructor, what is the use of constructor if we
don't instantiate abstract class? ............................................................................. 13
How to check if we can see the current code about aggregation
composition and inheritance, what is the practical use of it? ..................... 14
What are Composition and Aggregation with examples?.............................. 14
Explain Multilevel inheritance? ................................................................................ 15
What is abstraction, how it is different from encapsulation? ...................... 16
When to you use encapsulation and abstraction in your project?............. 17
How to achieve encapsulation? ............................................................................... 18
What is polymorphism and how can we achieve it? ....................................... 19
What is Method Overloading/Overriding? ........................................................... 20
Method overloading and overriding? ..................................................................... 21
Method overriding with access specifiers with example? .............................. 23
Methods Overriding with exception handling with example? ...................... 24
Can we have overloaded methods with different return type?................... 26
Can we override the static method? Why Can't we do that? ...................... 26

AJAY RATHOD 1
What is SOLID principles with example? ............................................................. 27
Cohesion vs Coupling, Explain that? ..................................................................... 28
What is the use of static keywords in java? ....................................................... 28
What is the Covariant type? ..................................................................................... 29
What exactly is abstraction what are the advantage of it? Concrete class
doing the same what is the advantage over concrete class? ...................... 30
What is default method its use? ............................................................................. 31
Can interface have no method in it? ..................................................................... 32
Exception rules for overriding? ................................................................................ 32
What is Static keyword?............................................................................................. 34
Difference between static variable and instance variables? ........................ 36
How to make class immutable? .............................................................................. 36
Different types of access modifiers? ..................................................................... 37
What is the use of protected members?.............................................................. 39

AJAY RATHOD 2
Introduction
Welcome to the Ultimate Guide to Mastering Java Developer Interviews!

Whether you're an aspiring Java Backend Developer with little to no


experience or someone with up to 10 years of expertise, you've come to
the right place! This book is tailor-made to be your ultimate companion in
preparing for your dream role.

Inside these pages, you'll find a curated collection of crucial interview


questions, carefully compiled based on my own experiences and
encounters. But it doesn't stop there! Not only will you find the questions
themselves, but I've also provided in-depth and relevant answers to each
one.

This comprehensive guide covers an extensive array of topics, leaving no


stone unturned in your preparation journey. From the fundamentals of
Object-Oriented Programming and Core Java to more advanced subjects
like Java-8, Spring Framework, Spring-Boot, Microservice architecture,
Memory Management in Java, REST principles, Design Patterns and
System Design, SQL and Hibernate-JPA, and various Coding and
Programming Questions – it's all here!

Not to mention, I've included Scenario-Based Interview Questions, delving


into practical situations that will test your problem-solving skills.
Additionally, you'll find a section dedicated to Miscellaneous topics,
ensuring you're well-versed in all the essential aspects.

The book also dives into the intricate world of Multithreading, an area that
many interviews focus on to assess your proficiency in concurrent
programming.

After you've explored the depths of this guide, I am confident that you'll
walk into your interview room with newfound confidence and expertise.
The knowledge you'll gain from these pages will undoubtedly set you
apart from the competition.

So, embrace this opportunity and embark on your journey toward


interview success with enthusiasm. Best of luck!

Best Regards,

Ajay Rathod

AJAY RATHOD 3
How to Prepare for a Java
Developer Interview
I will be sharing my preparation strategy for techies who want to hunt for
their next tech job. Over the course of three months, I extensively
prepared for a Java developer role. This preparation helped me clear
many interviews, including those with BIG FOUR companies. Developers
with 0–10 years of experience can apply this strategy.

Disclaimer: This article is not intended for FAANG companies; I am


referring to general tech companies ranging from MNCs to small-scale and
large-scale entities within the Indian Job Market.

In this article, I will elaborate on interview preparation and share my


strategies on how to maximize your chances of getting selected for an
interview.

Typical Interview Format

 Technical Round 1 (L1 round)

 Technical Round 2 (L2 round)

 Manager Round

 HR round

Usually, if you can clear the technical rounds, you are well on your way to
receiving an offer letter, as the manager and HR rounds primarily involve
discussions. Hence, our focus should be on preparing for the technical
rounds.

Technical Round Preparation Steps

The interview typically begins with an introduction, and the interviewer


may inquire about the project you have been working on.

Step 1: Know Your Current Project Inside and Out

a. Understand the functionality of the project, including its purpose and


the problems it solves for customers. Essentially, you should have a
comprehensive overview of your project's functions. b. Familiarize yourself
with the project's architecture and technical stack. You can also delve
deeper to comprehend the end-to-end flow. c. Discuss the technical stack
used in the project. For instance, specify the front-end framework (e.g.,
Angular, React), the backend technology (e.g., Java, Python), and the
database (e.g., PostgreSQL, Dynamo DB). d. Gain insight into the CI/CD

AJAY RATHOD 4
model employed. Many developers are unaware of the deployment
process, so this is a crucial aspect to understand.

Thoroughly studying the aforementioned project-related aspects will


empower you to steer the interview in your favor. Remember, your
responses often guide the interview.

Step 2: Java Developer Competencies

As a Java Developer, you should be well-versed in the following topics,


which will significantly enhance your likelihood of being selected.

 Object-Oriented Programming principles, including SOLID principles


(prepare for inheritance puzzles)

 Multithreading and Concurrency (prepare for Executor framework


and concurrency API)

 Collection framework (Comprehend the internal workings of each


collection data structure, such as HashMap, ConcurrentHashMap,
HashSet)

 Serialization (Understand its functioning)

 Design Patterns (Familiarize yourself with at least 4–5 design


patterns, including creational, behavioral, and structural patterns)

 Garbage Collection

 Java Generics

 Java 8 (Stream and Functional Programming—prepare to write Java


8 code for stream operations)

 SQL Queries (Be ready to write queries involving JOINS and


employee tables, such as retrieving the highest salary)

 Coding Practice (Solve a variety of Array and String problems)

 Memory Management (Stay informed about memory management


changes in Java 8 and above)

Proficiency in the aforementioned areas is crucial for interview success.


Candidates are typically evaluated based on their practical knowledge and
ability to write programs and SQL queries using Java. These skills
significantly contribute to interview performance.

Remember, diligent preparation and a strong grasp of these concepts will


greatly improve your chances of excelling in your Java Developer
interview. Good luck!

AJAY RATHOD 5
How to introduce yourself
Tell me about yourself, tell me about skills?
"Tell me about yourself" and "Tell me about your skills" are common
interview questions that can be challenging to answer. Here are some tips
on how to tackle these questions:

Prepare ahead of time: Spend some time thinking about your


strengths, experiences, and achievements that are relevant to the position
you are applying for. Write them down and practice talking about them
out loud.

Keep it relevant: When answering the question "Tell me about yourself,"


focus on your professional experiences and achievements that are
relevant to the position you are applying for. You can also mention your
personal interests if they relate to the job.

Be concise: Keep your answers brief and to the point. Don't ramble on or
share irrelevant information. Stick to the main points and be clear and
concise.

Highlight your skills: When asked about your skills, provide specific
examples of how you have used them in the past to achieve success. Talk
about your strengths and how they will benefit the company. Be sure to
include both technical and soft skills, such as problem-solving,
communication, and teamwork.

Be honest: It's important to be truthful when answering these questions.


Don't exaggerate or make up skills or experiences that you don't actually
possess.

Practice: It's a good idea to practice answering these questions with a


friend or family member to help you feel more comfortable and confident
during the actual interview.

Tell me about your project & architecture please explain it?


Draw the architecture, framework and technology used?
When answering the question "Tell me about your project and
architecture," it's important to provide a clear and concise overview of the
project and the underlying architecture. Here are some tips to help you
tackle this question:

Start with an overview: Begin by giving a brief overview of the project and
the business problem it was designed to solve. This will help provide
context for the architecture you will describe.

AJAY RATHOD 6
Discuss the architecture: Provide an explanation of the underlying
architecture that was used in the project. This should include a high-level
overview of the components and how they interact with each other. You
can also discuss the rationale for choosing this architecture and any trade-
offs that were made.

Describe the design decisions: Talk about the design decisions that
were made during the project. This could include how the architecture was
designed to meet specific performance requirements, how the system was
designed to be scalable, or how it was designed to be maintainable.

Discuss the implementation: Describe how the architecture was


implemented and any challenges that were encountered during
implementation. This could include any optimizations that were made or
any trade-offs that were made to meet specific requirements.

Highlight your role: Be sure to discuss your role in the project and how
you contributed to the architecture design and implementation. This could
include any specific tasks you performed or any technical challenges you
helped overcome.

Use visual aids: If possible, use diagrams or other visual aids to help
illustrate the architecture and design decisions. This can help the
interviewer better understand your explanation and provide a more
comprehensive answer.

Remember to stay focused on the most relevant aspects of the project


and architecture, and be sure to highlight your role and contributions to
the project. Be clear and concise in your explanation, and use examples
and visual aids where possible to help support your answer.

Best practices to follow while developing an application?


There are several best practices to follow during software development to
ensure a high-quality product and efficient development process. Here are
some of the most important ones:

Plan and prioritize: Before starting development, make sure to plan the
project thoroughly and prioritize tasks based on their importance and
urgency.

Follow a consistent process: Use a consistent development process, such


as agile or waterfall, to ensure a structured and predictable development
process.

Use version control: Use a version control system, such as Git, to manage
and track changes to the codebase.

AJAY RATHOD 7
Test early and often: Test the software early and often to catch bugs and
errors before they become more difficult to fix.

Use automation: Use automation tools, such as continuous integration and


deployment (CI/CD) pipelines, to automate repetitive tasks and ensure
consistency.

Write clean and modular code: Write clean, modular, and maintainable
code to make it easier to maintain and extend the software over time.

Document the code: Document the code thoroughly, including comments


and documentation, to make it easier for other developers to understand
and work with the code.

Use appropriate tools and technologies: Use appropriate tools and


technologies that are well-suited for the project requirements and team's
skills.

Collaborate effectively: Foster effective collaboration within the team,


including communication, code reviews, and regular meetings to ensure
everyone is aligned and working towards the same goals.

Continuously improve: Continuously evaluate and improve the


development process and incorporate feedback from users to improve the
software over time.

By following these best practices, software development teams can create


high-quality software that is maintainable, scalable, and efficient to
develop.

What challenging things you have done it of spring and


hibernate and database?
Tell them about any functionality or Module, MVP you have developed.

Explain the code and flow of the project in and out of it?
When asked to explain the code and flow of a project, it's important to
provide a clear and concise overview of the project and how it works. Here
are some tips to help you answer this question:

Start with an overview: Begin by giving a brief overview of the project and
its purpose. This will help provide context for the code and flow you will
describe.

Discuss the architecture: Provide an explanation of the underlying


architecture that was used in the project. This should include a high-level
overview of the components and how they interact with each other.

AJAY RATHOD 8
Describe the code flow: Describe how the code flows through the different
components of the project. This should include an explanation of the
different modules, functions, and classes that make up the codebase.

Explain the logic: Explain the logic behind the code and how it implements
the functionality of the project. This should include an explanation of the
algorithms and data structures used in the code.

Use visual aids: If possible, use diagrams or other visual aids to help
illustrate the code flow and architecture. This can help the listener better
understand your explanation and provide a more comprehensive answer.

Highlight your contributions: Be sure to discuss your contributions to the


project and how you contributed to the code and flow. This could include
any specific tasks you performed or any technical challenges you helped
overcome.

Provide examples: Provide specific examples of how the code and flow
work in different scenarios. This can help illustrate the functionality of the
project and provide a more concrete understanding of how it works.

Remember to stay focused on the most relevant aspects of the project


and code flow, and be sure to highlight your role and contributions to the
project. Be clear and concise in your explanation, and use examples and
visual aids where possible to help support your answer.

How do you build your code, how to do packaging?


When asked how you build your code and package it, here are some tips
to help you provide a comprehensive answer:

Build process: Start by explaining the process you follow to build your
code. This should include a high-level overview of the tools and
technologies you use to compile and build the codebase. For example, you
might use Maven, Gradle, or Ant to build your code.

Dependencies: Explain how you manage dependencies in your project.


This should include an explanation of how you include external libraries
and frameworks in your codebase, and how you manage the versioning of
these dependencies.

Testing: Explain how you ensure the quality of your code through testing.
This should include an explanation of the different types of tests you use,
such as unit tests, integration tests, and acceptance tests, and how you
automate and run these tests.

Packaging: Describe how you package your code for deployment. This
should include an explanation of how you package the code into a
deployable artifact, such as a JAR or WAR file. You should also explain any

AJAY RATHOD 9
steps you take to optimize the package size and reduce any unnecessary
dependencies.

Continuous Integration: Discuss any continuous integration or delivery


practices that you follow. This should include an explanation of how you
automate the build and packaging process, and how you integrate testing
and deployment into your development process.

Version Control: Explain how you use version control systems like Git to
manage and maintain the codebase, and how you ensure that the code is
always in a deployable state.

Documentation: Explain how you document the code and the build
process, and how you ensure that the documentation stays up-to-date as
the codebase evolves.

By covering these key aspects of your build and packaging process, you
can demonstrate your knowledge and expertise in software development,
and show how you ensure the quality and maintainability of your code. Be
sure to provide specific examples and use cases wherever possible to
support your answer.

AJAY RATHOD 10
Object Oriented Programming
Tell me about OOPS concept in java?
Four principle of OOP? Abstraction, encapsulation, inheritance
polymorphism?
The four principles of Object-Oriented Programming (OOP) are:

Encapsulation: This refers to the practice of hiding the internal workings


of an object and exposing only the necessary functionality. The data and
behaviour of an object are encapsulated within the object, and can only be
accessed through well-defined interfaces.

Inheritance: Inheritance allows objects to inherit properties and


behaviours from other objects. Inheritance allows for the creation of
hierarchical relationships between classes, with parent classes passing
down their characteristics to their child classes.

Polymorphism: Polymorphism refers to the ability of objects to take on


many forms, and is achieved through the use of inheritance, overloading
and overriding methods, and interfaces. Polymorphism allows for greater
flexibility and reuse of code.

Abstraction: Abstraction refers to the process of identifying common


patterns and extracting essential features of objects, creating classes from
these patterns. Abstraction allows for the creation of higher-level concepts
that can be used in multiple contexts, and can simplify complex systems.

Inheritance vs composition?
Inheritance allows a class (called a subclass) to inherit properties and
behaviors from another class (called a superclass). The subclass can then
add or modify these properties and behaviors as needed. It's useful for
creating hierarchies of related classes and sharing code and functionality.

For example, if we have an Animal class, a Mammal class, and a Cat class,
the Cat class can inherit properties and behaviors from both Animal and
Mammal classes while adding its own specific methods.

Composition allows a class to be composed of other objects. This means


that a class can have references to other objects as its properties and use
them to delegate tasks or behaviors. It's useful for creating complex
objects from simpler ones and enabling dynamic composition at runtime.

For instance, a Car class can be composed of objects such as an Engine,


Wheels, Seats, etc. The Car class can then utilize these objects to perform
various tasks.

AJAY RATHOD 11
Abstraction vs polymorphism?
Abstraction is the process of identifying common patterns and extracting
essential features of objects to create classes. It allows us to simplify
complex systems by creating higher-level concepts that can be used in
different contexts. Abstraction involves defining interfaces, classes, and
objects that provide the necessary details for the system's use case while
hiding unnecessary implementation details.

For example, a Car class can be abstracted as a Vehicle class with


essential properties and methods like accelerate(), brake(), and turn().
This abstraction allows us to create various types of vehicles (Car, Bike,
Bus, Truck) that implement these essential features.

Polymorphism refers to objects' ability to take on different forms,


achieved through inheritance, method overloading and overriding, and
interfaces. Polymorphism provides flexibility and code reuse. Objects can
behave differently depending on the context in which they are used.

For instance, a Vehicle class may have a drive() method implemented


differently by subclasses like Car, Bike, Bus, etc. Despite the method's
common name, it can exhibit different behaviors based on the specific
implementation in each subclass. This flexibility allows for code reuse.

Abstract class vs interface?


An abstract class is a class that can't be instantiated and is meant to be
extended by other classes. It can have both abstract and non-abstract
methods, instance variables, constructors, and other typical class
features. An abstract method is a method without an implementation that
must be overridden by any concrete subclass. Abstract classes are useful
for creating a class hierarchy template, where some methods are defined
in the abstract class and others are implemented by the concrete
subclasses.

For example, consider an abstract class called "Shape" with properties like
color, abstract methods for area and perimeter calculations, and a
toString method.

Interfaces, on the other hand, are collections of abstract methods and


constants that define a contract for a class. They can't contain
implementation code, only method and constant signatures. Interfaces are
useful for defining a common behavior that can be implemented by
multiple classes, regardless of their class hierarchy.

For instance, a "Drawable" interface can have methods like draw and fill,
which must be implemented by any class that implements the interface.

A class can implement one or multiple interfaces and must provide


implementations for all the methods defined in the interface. For example,

AJAY RATHOD 12
a "Circle" class can implement the "Drawable" interface with its own
implementations for the draw and fill methods.

Abstract class with constructor, what is the use of constructor


if we don't instantiate abstract class?
In Java, an abstract class can have a constructor just like any other class.
The purpose of a constructor in an abstract class is to initialize any
instance variables or perform any setup operations that are common to all
subclasses.

Although you cannot instantiate an abstract class directly, you can still
use its constructor indirectly when you create an instance of a subclass.
When you create an instance of a subclass, the constructor of the abstract
class is automatically called before the constructor of the subclass. This
allows you to set up any common state or behaviour that the subclasses
will share.

Here's an example of an abstract class with a constructor:

public abstract class Shape {

protected String name;

public Shape(String name) {

this.name = name;

public abstract double getArea();

public abstract double getPerimeter();

In this example, the Shape class is abstract and has an instance variable
name and a constructor that takes a String parameter. The constructor
initializes the name variable with the value passed in. The Shape class
also has two abstract methods, getArea and getPerimeter, that must be
implemented by any concrete subclass.

A concrete subclass of Shape, such as Circle or Rectangle, can then be


created and will inherit the name variable and constructor from the Shape
class. When an instance of a subclass is created, the Shape constructor is
called automatically before the subclass constructor, allowing any
necessary setup to be performed.

AJAY RATHOD 13
So even though you cannot instantiate an abstract class directly, the
constructor can still be useful for initializing common state or behaviour
that subclasses will share.

How to check if we can see the current code about aggregation


composition and inheritance, what is the practical use of it?
To check if the current code contains examples of aggregation,
composition, and inheritance, you need to look for the relevant syntax and
usage patterns in the code.

Here are some pointers for identifying these concepts in code:

Inheritance: Look for classes that extend or inherit from other classes.
This is typically indicated by the extends keyword in Java, for example:
public class Car extends Vehicle {...}. Inheritance is used to create a
hierarchy of classes where subclasses inherit properties and methods from
their parent classes.

Composition: Look for objects that contain other objects as instance


variables. This is typically indicated by object instantiation within another
object's constructor, for example: public class Person { private Job job;
public Person(Job job) { this.job = job; }}. Composition is used to build
complex objects by combining simpler objects.

Aggregation: Look for objects that have references to other objects as


instance variables, but do not own or create them. This is typically
indicated by a "has-a" relationship between objects, for example: public
class University { private List<Student> students; public
University(List<Student> students) { this.students = students; }}.
Aggregation is used to represent relationships between objects without
tightly coupling them together.

To get a better understanding of how these concepts are used in code,


you may want to read through the codebase and look for patterns that
indicate their usage. Additionally, you may want to search for specific
keywords and syntax related to inheritance, composition, and
aggregation, such as extends, implements, and new. Finally, you may also
want to talk to other developers or review documentation to understand
how these concepts are being used in the codebase.

What are Composition and Aggregation with examples?


Composition and aggregation are two types of object-oriented
programming concepts that describe the relationship between objects.

Composition is a strong type of association where an object is made up of


one or more objects of other classes. For example, a car is composed of
various parts such as wheels, engine, transmission, etc. The car class has

AJAY RATHOD 14
an object of the wheel class, engine class, and transmission class as its
member variables.

Aggregation is a weak type of association where an object contains a


reference to one or more objects of other classes. For example, a
university class has a collection of student classes as its member variable.
The student class has an object of the university class as its member
variable.

In summary, composition is a relationship where an object is dependent


on the other objects, whereas aggregation is a relationship where an
object can exist independently of the other objects.

Explain Multilevel inheritance?


Multilevel inheritance is a type of inheritance in object-oriented
programming (OOP) where a derived class (subclass) is created from
another derived class, which itself was derived from a base class
(superclass).

In multilevel inheritance, each derived class inherits the characteristics of


the class above it in the hierarchy. This means that a subclass not only
has all the features of its immediate superclass, but also those of all its
ancestors up the hierarchy chain.

Here's an example to illustrate multilevel inheritance:

class Animal {

void eat() {

System.out.println("Eating...");

class Dog extends Animal {

void bark() {

System.out.println("Barking...");

class Bulldog extends Dog {

void guard() {

System.out.println("Guarding...");

AJAY RATHOD 15
}

In this example, Animal is the base class, Dog is a derived class from
Animal, and Bulldog is a derived class from Dog.

Animal has a single method eat(). Dog inherits eat() from Animal and
adds a new method bark(). Bulldog inherits both eat() and bark() from
Dog and adds a new method guard().

Now, an instance of Bulldog can access all the methods of its immediate
superclass (Dog), as well as all the methods of its ancestor superclass
(Animal). For example:

Bulldog bulldog = new Bulldog();

bulldog.eat(); // output: Eating...

bulldog.bark(); // output: Barking...

bulldog.guard(); // output: Guarding...

This example demonstrates how multilevel inheritance can be used to


create a hierarchy of classes that inherit and extend behavior from each
other. However, it is important to use inheritance judiciously to avoid
creating overly complex and tightly-coupled class hierarchies.

What is abstraction, how it is different from encapsulation?


Abstraction and encapsulation are two important concepts in object-
oriented programming, but they refer to different aspects of object-
oriented design.

Abstraction is the process of identifying the essential characteristics of an


object or system and ignoring the non-essential details. Abstraction allows
you to work with objects at a higher level of abstraction, focusing on the
essential features and behaviours rather than the implementation details.
Abstraction is achieved in Java through the use of abstract classes and
interfaces.

Encapsulation, on the other hand, is the process of hiding the


implementation details of an object or system from the outside world.
Encapsulation allows you to protect the data and behaviour of an object,
and prevent other objects from accessing or modifying it directly.
Encapsulation is achieved in Java through the use of access modifiers
(public, private, protected) and getter and setter methods.

So while abstraction and encapsulation are related concepts, they are


different in their focus and purpose. Abstraction is concerned with

AJAY RATHOD 16
identifying the essential characteristics of an object or system, while
encapsulation is concerned with hiding the implementation details of an
object or system from the outside world.

In practice, abstraction and encapsulation often work together to create


well-designed, maintainable, and extensible software systems. Abstraction
allows you to create a high-level view of a system, while encapsulation
allows you to protect the details of the implementation from the outside
world. Together, abstraction and encapsulation provide a powerful way to
design complex systems that are easy to understand, modify, and
maintain.

When to you use encapsulation and abstraction in your


project?
Encapsulation and abstraction are two important concepts in object-
oriented programming, and they are used in different ways in different
parts of a project.

Encapsulation is used to protect the internal state of an object and to


control how other objects can access or modify that state. It is typically
used in data modelling, where we define classes that represent real-world
entities and their properties.

For example, if we were building a system to manage a library, we might


define a Book class that has properties like title, author, and isbn. We
would use encapsulation to ensure that these properties are not accessible
or modifiable from outside the Book class, except through carefully
designed methods like getTitle() and setAuthor().

Abstraction, on the other hand, is used to hide the implementation details


of a class or component and to present a simpler, higher-level interface to
other parts of the system. It is typically used in system design and
architecture, where we define components and their interfaces.

For example, if we were building a web application, we might define a


UserService component that provides methods for creating, updating, and
retrieving user accounts. We would use abstraction to ensure that other
components in the system do not need to know how the UserService is
implemented, but can simply use its interface to perform the necessary
actions.

In general, encapsulation and abstraction are used together in object-


oriented programming to create robust, maintainable, and scalable
systems. Encapsulation is used to protect the internal state of objects and
to control how other objects can access or modify that state, while
abstraction is used to hide the implementation details of components and
to present a simpler, higher-level interface to other parts of the system.

AJAY RATHOD 17
How to achieve encapsulation?
Encapsulation is achieved in Java through the use of access modifiers and
getter and setter methods.

Access modifiers control the visibility of variables and methods in a class.


There are three access modifiers in Java: public, private, and protected.

Public: Public variables and methods can be accessed from anywhere in


the program.

Private: Private variables and methods can only be accessed within the
same class.

Protected: Protected variables and methods can be accessed within the


same class, and by subclasses and classes in the same package.

By default, if you don't specify an access modifier, the variable or method


is considered to have "package" or "default" access, which means it can
be accessed within the same package.

Here's an example of how to use access modifiers to achieve


encapsulation:

public class Person {

private String name;

private int age;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getAge() {

return age;

AJAY RATHOD 18
public void setAge(int age) {

if (age < 0) {

throw new IllegalArgumentException("Age cannot be negative");

this.age = age;

In this example, the Person class has two private variables, name and
age. These variables are not directly accessible from outside the class,
which means that other classes cannot modify or access them directly.

To allow other classes to access these variables, we provide public getter


and setter methods for name and age. The getter methods allow other
classes to retrieve the values of these variables, while the setter methods
allow other classes to modify their values.

Note that we can also add validation logic to the setter methods to ensure
that the values being set are valid. In this example, the setAge method
throws an exception if the age is negative.

By using access modifiers and getter and setter methods, we can achieve
encapsulation in Java. This allows us to protect the data and behavior of
our objects and prevent other objects from accessing or modifying them
directly, which makes our code more robust and maintainable.

What is polymorphism and how can we achieve it?


Polymorphism is the ability of objects of different classes to be treated as
if they are of the same type. It allows us to write code that can work with
objects of different types in a uniform way, without needing to know the
specific class of each object.

In Java, polymorphism is achieved through two mechanisms: method


overloading and method overriding.

Method overloading is when a class has two or more methods with the
same name, but different parameters. When a method is called, the
compiler determines which method to call based on the number and types
of the arguments passed to it.

public class Calculator {

public int add(int x, int y) {

return x + y;

AJAY RATHOD 19
}

public double add(double x, double y) {

return x + y;

In this example, the Calculator class has two methods named add, one
that takes two integers and one that takes two doubles. When the add
method is called, the compiler determines which version of the method to
call based on the types of the arguments passed to it.

Method overriding is when a subclass provides its own implementation of


a method that is already defined in its superclass. The subclass method
must have the same name, return type, and parameter list as the
superclass method.

public class Animal {

public void speak() {

System.out.println("Animal speaks");

public class Dog extends Animal {

public void speak() {

System.out.println("Dog barks");

In this example, the Animal class has a method named speak. The Dog
class extends the Animal class and provides its own implementation of the
speak method. When we call the speak method on a Dog object, the Dog
version of the method is called instead of the Animal version.

Polymorphism allows us to write code that can work with objects of


different types in a uniform way, without needing to know the specific
class of each object. It makes our code more flexible and easier to
maintain, and is a key feature of object-oriented programming.

What is Method Overloading/Overriding?


Method overloading and overriding are two concepts in object-oriented
programming that describe how methods in a class can be used.

AJAY RATHOD 20
Method overloading is the ability of a class to have multiple methods with
the same name but with different parameters. This is also known as
"compile-time polymorphism" or "function overloading" in some
languages. For example, a class Calculator might have multiple methods
with the name add, but with different parameters such as add (int a, int
b) and add (double a, double b).

Method overriding is the ability of a subclass to provide a different


implementation of a method that is already provided by its superclass.
This is also known as "runtime polymorphism" or "function overriding".
The method in the subclass has the same name, return type and
parameters as the method in the superclass. The purpose of method
overriding is to change the behaviour of the method in the subclass.

In summary, Method overloading allows multiple methods with the same


name in a class but with different parameters, whereas Method overriding
allows a subclass to provide a different implementation of a method that
is already provided by its superclass.

Method overloading and overriding?


Method overloading and method overriding are both concepts in object-
oriented programming that involve defining methods in classes.

Method overloading is the ability to define multiple methods in the same


class with the same name, but with different parameters. The parameters
can differ in number, type, or order. The compiler decides which method
to call based on the parameters passed to it. Here's an example:

public class Calculator {

public int add(int x, int y) {

return x + y;

public int add(int x, int y, int z) {

return x + y + z;

public double add(double x, double y) {

return x + y;

AJAY RATHOD 21
}

In this example, Calculator defines three different add() methods with the
same name but different parameters. The first method takes two int
arguments, the second takes three int arguments, and the third takes two
double arguments. The compiler decides which method to call based on
the number and type of arguments passed to it.

Method overriding, on the other hand, is the ability to define a method in


a subclass that has the same name and parameters as a method in its
superclass. When the method is called on an object of the subclass, the
method in the subclass is executed instead of the method in the
superclass. Here's an example:

public class Animal {

public void makeSound() {

System.out.println("The animal makes a sound");

public class Dog extends Animal {

@Override

public void makeSound() {

System.out.println("The dog barks");

In this example, Animal defines a makeSound() method that prints a


message. Dog overrides this method with its own implementation that
prints a different message. When makeSound() is called on a Dog object,
the overridden method in Dog is executed, producing the output "The dog
barks".

In summary, method overloading is the ability to define multiple methods


with the same name but different parameters in a class, while method
overriding is the ability to define a method in a subclass with the same
name and parameters as a method in its superclass, with the subclass's

AJAY RATHOD 22
method taking precedence over the superclass's method when called on
an object of the subclass.

Method overriding with access specifiers with example?


In Java, method overriding is when a subclass provides its own
implementation of a method that is already defined in its superclass. The
subclass method must have the same name, return type, and parameter
list as the superclass method.

Access specifiers determine the visibility of a method, and they can also
be used when overriding methods. When overriding a method, the access
specifier of the overriding method cannot be more restrictive than the
access specifier of the overridden method. In other words, if the
overridden method is public, the overriding method must also be public or
less restrictive.

Here is an example of method overriding with access specifiers: public


class Animal {

public void speak() {

System.out.println("Animal speaks");

protected void eat() {

System.out.println("Animal eats");

public class Dog extends Animal {

@Override

public void speak() {

System.out.println("Dog barks");

@Override

protected void eat() {

System.out.println("Dog eats");

AJAY RATHOD 23
}

In this example, the Animal class has a method named speak that is
public, and a method named eat that is protected. The Dog class extends
the Animal class and provides its own implementations of the speak and
eat methods.

The speak method in the Dog class overrides the speak method in the
Animal class and is also public. The eat method in the Dog class overrides
the eat method in the Animal class and is also protected. Since the eat
method in the Animal class is also protected, the access specifier of the
eat method in the Dog class can be the same or less restrictive, but not
more restrictive.

In this way, we can use method overriding to provide our own


implementations of methods that are defined in a superclass, while also
adhering to the access specifiers of the original methods. This allows us to
customize the behaviour of our subclasses while maintaining the structure
and visibility of the superclass.

Methods Overriding with exception handling with example?


In Java, when overriding a method, the overridden method can throw
exceptions, and the overriding method can choose to throw the same
exceptions or a subset of them. Here's an example of method overriding
with exception handling:

public class Animal {

public void speak() throws Exception {

System.out.println("Animal speaks");

public void eat() throws Exception {

System.out.println("Animal eats");

public class Dog extends Animal {

@Override

public void speak() throws IOException {

System.out.println("Dog barks");

throw new IOException("Exception from Dog.speak");

AJAY RATHOD 24
}

@Override

public void eat() {

System.out.println("Dog eats");

In this example, the Animal class has two methods: speak and eat. Both
methods are declared to throw an Exception.

The Dog class extends the Animal class and overrides both the speak and
eat methods.

The speak method in the Dog class overrides the speak method in the
Animal class and throws an IOException. The IOException is a subclass of
Exception, so this is allowed.

The eat method in the Dog class overrides the eat method in the Animal
class but does not throw any exceptions.

When calling these methods, we can catch the exceptions that are thrown.
For example:

public static void main(String[] args) {

Animal animal = new Dog();

try {

animal.speak();

} catch (IOException e) {

System.out.println("Caught IOException: " + e.getMessage());

} catch (Exception e) {

System.out.println("Caught Exception: " + e.getMessage());

try {

animal.eat();

} catch (Exception e) {

System.out.println("Caught Exception: " + e.getMessage());

AJAY RATHOD 25
}

In this example, we create an instance of the Dog class and assign it to a


variable of type Animal. We then call the speak and eat methods on this
object.

Since the speak method in the Dog class throws an IOException, we catch
that exception specifically and print out its message. If the speak method
in the Dog class threw a different type of exception, such as
RuntimeException, it would not be caught by this catch block.

The eat method in the Dog class does not throw any exceptions, so the
catch block for Exception will not be executed. If the eat method in the
Dog class did throw an exception, it would be caught by this catch block.

Can we have overloaded methods with different return type?


No, we cannot have overloaded methods with only different return types.
Overloaded methods must have the same method name and parameters,
but they can have different return types only if the method parameters
are also different. The reason for this is that the return type alone is not
enough information for the compiler to determine which method to call at
compile time. For example, consider the following code:

public class Calculator {

public int add(int x, int y) {

return x + y;

public double add(int x, int y) {

return (double) (x + y);

In this example, we have two add() methods with the same parameters,
but different return types (int and double). This will cause a compilation
error because the compiler cannot determine which method to call based
on the return type alone.

Can we override the static method? Why Can't we do that?


No, it is not possible to override a static method in Java. A static method
is associated with the class and not with an object, and it can be called
directly on the class, without the need of creating an instance of the class.

AJAY RATHOD 26
When a subclass defines a static method with the same signature as a
static method in the superclass, the subclass method is said to hide the
superclass method. This is known as method hiding. The subclass method
is not considered an override of the superclass method, it is considered a
new method and it hides the superclass method, but it doesn't override it.

In summary, since a static method is associated with the class, not an


object and it is directly callable on the class, it is not possible to override a
static method in Java, instead, it is hidden by subclass method with the
same signature.

What is SOLID principles with example?


SOLID is an acronym that represents five principles of object-oriented
design that aim to make software more maintainable, flexible, and easy to
understand. Here are the explanations of each of the five SOLID
principles, along with examples:

Single Responsibility Principle (SRP): This principle states that a class


should have only one reason to change. In other words, a class should
have only one responsibility or job. For example, if we have a class named
User, it should only be responsible for handling user-related functionalities
such as authentication, user data management, etc. It should not be
responsible for other unrelated functionalities like sending emails or
managing payment transactions.

Open/Closed Principle (OCP): This principle states that a class should be


open for extension but closed for modification. This means that we should
be able to add new functionalities or behaviors to a class without changing
its existing code. For example, instead of modifying an existing Payment
class to add support for a new payment method, we can create a new
PaymentMethod class that implements a Payment interface and inject it
into the Payment class.

Liskov Substitution Principle (LSP): This principle states that derived


classes should be able to replace their base classes without affecting the
correctness of the program. In other words, if we have a base class
Animal and a derived class Dog, we should be able to use the Dog class
wherever we use the Animal class. For example, if we have a method that
takes an Animal parameter and performs some action, we should be able
to pass a Dog object to that method without any issues.

Interface Segregation Principle (ISP): This principle states that a class


should not be forced to implement interfaces it does not use. In other
words, we should separate interfaces that are too large or general into

AJAY RATHOD 27
smaller and more specific interfaces. For example, instead of having a
single Payment interface that includes all payment methods, we can have
separate interfaces like CreditCardPayment, PayPalPayment, etc.

Dependency Inversion Principle (DIP): This principle states that high-level


modules should not depend on low-level modules. Instead, both should
depend on abstractions. This means that we should rely on abstractions,
rather than concrete implementations. For example, instead of depending
on a specific database implementation in a class, we should depend on a
database interface, which can be implemented by different databases.
This allows for easier testing, maintenance, and scalability.

Cohesion vs Coupling, Explain that?


Cohesion refers to the degree to which the elements within a module or
component work together to achieve a single, well-defined purpose. High
cohesion means that the elements within a module are strongly related
and work together towards a common goal, while low cohesion means
that the elements are loosely related and may not have a clear purpose.

Coupling, on the other hand, refers to the degree of interdependence


between modules or components. High coupling means that a change in
one module or component will likely affect other modules or components,
while low coupling means that changes in one module or component will
have minimal impact on other modules or components.

In general, software design principles strive for high cohesion and low
coupling, as this leads to code that is more modular, maintainable, and
easier to understand and change.

What is the use of static keywords in java?


In Java, the "static" keyword is used to indicate that a member variable or
method belongs to a class rather than an instance of the class.

When a variable is declared as "static", it is shared among all instances of


the class and can be accessed directly through the class name, without
needing to create an object of the class. This can be useful for variables
that are common to all instances of the class, such as a count of the
number of instances that have been created.

When a method is declared as "static", it can be called directly through


the class name, without needing to create an object of the class. This can
be useful for methods that do not depend on the state of any specific
object, such as a utility method that performs a common calculation.

AJAY RATHOD 28
Additionally, a static block is a block of code which is executed only once
when the class is loaded in memory by JVM, before the creation of any
instance of the class, and can be used to perform any one-time
initialization.

In summary, the static keyword is used to indicate that a member belongs


to a class rather than an instance of a class, and it is shared among all
instances of the class, can be accessed directly through class name, and
can be used in situations where you don't need to create an object of the
class.

What is the Covariant type?


Covariant type refers to the ability to use a subclass type in place of its
superclass type. In other words, it allows a subclass to be used in place of
its superclass. This feature is supported by some programming languages
such as Java and C#.

For example, if class B is a subclass of class A, then an object of class B


can be used wherever an object of class A is expected.
Here is an example in Java:

class A { }

class B extends A { }

A a = new A();

B b = new B();

a = b; // valid

In the above example, the variable "a" is of type A, and the variable "b" is
of type B. However, the assignment "a = b" is valid, because B is a
subclass of A.

Covariant return types allow a method to return a subclass type in place


of its superclass type.

class A { }

class B extends A { }

class C {

A getA() { return new A(); }

AJAY RATHOD 29
B getB() { return new B(); }

In the above example, the method getA() returns an object of type A, and
the method getB() returns an object of type B. Because B is a subclass of
A, the method getB() can be overridden to return B instead of A.

In summary, Covariant type refers to the ability to use a subclass type in


place of its superclass type, this feature is supported by some
programming languages such as Java and C#. It allows a subclass to be
used in place of its superclass and covariant return types allow a method
to return a subclass type in place of its superclass type.

What exactly is abstraction what are the advantage of it?


Concrete class doing the same what is the advantage over
concrete class?
Abstraction is a fundamental concept in object-oriented programming that
allows you to create models of complex systems by focusing on the
essential features and ignoring the non-essential details. Abstraction is the
process of identifying and separating the essential characteristics of an
object or system from the irrelevant details, so that you can work with it
at a higher level of abstraction.

In software development, abstraction is achieved through the use of


abstract classes and interfaces. An abstract class is a class that cannot be
instantiated and may contain abstract methods, which are methods that
have no implementation and must be implemented by concrete
subclasses. An interface is a collection of abstract methods that defines a
set of behaviours that a class can implement.

The advantages of abstraction include:

Encapsulation: Abstraction helps to encapsulate the implementation


details of a system by focusing on the essential features and hiding the
non-essential details. This makes it easier to manage and maintain the
system, and reduces the risk of errors or bugs caused by changes to the
implementation.

Flexibility: Abstraction makes it easier to modify or extend a system


without affecting the rest of the system. By defining a set of behaviors
that a class can implement, interfaces allow you to change the
implementation of a class without affecting the way it is used by other
classes.

Reusability: Abstraction allows you to create reusable components that


can be used in different contexts. By defining a set of behaviors that a

AJAY RATHOD 30
class can implement, interfaces provide a standard way of interacting with
objects, making it easier to reuse components in different parts of a
system.

Testability: Abstraction makes it easier to test a system by allowing you to


focus on the essential behaviors of a class or system. By defining a set of
behaviors that a class can implement, interfaces provide a clear and
testable specification of how a class should behave.

In comparison to a concrete class, an abstract class provides a higher


level of abstraction and allows you to focus on the essential behaviors of a
class or system without worrying about the implementation details.
Concrete classes, on the other hand, provide a specific implementation of
a class or system and may contain a lot of non-essential details. The
advantage of using an abstract class over a concrete class is that it
provides greater flexibility, reusability, and testability, and allows you to
work at a higher level of abstraction.

What is default method its use?


A default method is a method defined in an interface that has a default
implementation. Default methods were introduced in Java 8 to allow
interfaces to be extended without breaking existing implementations.

Prior to Java 8, interfaces could only contain method signatures, which


meant that any class that implemented an interface was required to
provide an implementation for all of its methods. This could be
problematic when you wanted to add new methods to an existing
interface, because it would break all of the existing implementations.

With default methods, you can provide a default implementation for a


method in an interface, which means that classes that implement the
interface are not required to provide their own implementation. If a class
does not provide its own implementation for a default method, it will use
the default implementation defined in the interface.

Default methods are useful for extending existing interfaces without


breaking existing implementations. They can also be used to provide a
common implementation for a method that is applicable to all classes that
implement the interface.

For example, consider an interface for a collection of items:

public interface Collection<T> {

void add(T item);

AJAY RATHOD 31
boolean contains(T item);

int size();

default boolean isEmpty() {

return size() == 0;

This interface defines three methods for adding items to the collection,
checking if an item is contained in the collection, and getting the size of
the collection. It also defines a default method, isEmpty(), that returns
true if the size of the collection is 0.

Classes that implement this interface are not required to provide their own
implementation for isEmpty(), because a default implementation is
already provided in the interface. However, they can override the default
implementation if they need to provide a different behavior.

Can interface have no method in it?


An interface without any methods is called a "marker interface". It is used
to mark a class as having some specific behavior or property, without
specifying any methods for that behavior or property.

For example, the Serializable interface in Java has no methods:

public interface Serializable {

However, classes that implement the Serializable interface gain the ability
to be serialized and deserialized, which is the behavior that the
Serializable marker interface indicates.

Here's an example of using a marker interface:

In this example, we define a marker interface MyMarkerInterface with no


methods. We then define a class MyClass that implements the
MyMarkerInterface interface. This indicates that MyClass has some specific
behavior or property that is indicated by the MyMarkerInterface marker
interface. However, since MyMarkerInterface has no methods, MyClass
does not need to implement any methods as a result of implementing the
MyMarkerInterface interface.

Exception rules for overriding?


When overriding a method in Java, there are some rules that must be
followed regarding exceptions:

AJAY RATHOD 32
The overriding method can throw the same exceptions as the overridden
method, or any subset of those exceptions.

The overriding method can also throw unchecked exceptions, even if the
overridden method does not.

The overriding method cannot throw checked exceptions that are not in
the same class hierarchy as the exceptions thrown by the overridden
method. This means that the overriding method cannot throw checked
exceptions that are more general than those thrown by the overridden
method. However, it can throw more specific checked exceptions or
unchecked exceptions.

If the overridden method does not throw any exceptions, the overriding
method cannot throw checked exceptions.

Here's an example to illustrate these rules:

class Parent {

void foo() throws IOException {

// implementation goes here

class Child extends Parent {

// this is a valid override

void foo() throws FileNotFoundException {

// implementation goes here

// this is not a valid override

void foo() throws Exception {

// implementation goes here

// this is a valid override

void foo() throws RuntimeException {

// implementation goes here

AJAY RATHOD 33
}

// this is not a valid override

void foo() throws SQLException {

// implementation goes here

// this is a valid override, since it does not throw any exceptions

void foo() {

// implementation goes here

In this example, Parent has a method foo() that throws an IOException.


Child overrides this method and follows the rules for exception handling:

The first override is valid, since FileNotFoundException is a subclass of


IOException.

The second override is not valid, since Exception is a more general


exception than IOException.

The third override is valid, since RuntimeException is an unchecked


exception and can be thrown even if the overridden method does not
throw any exceptions.

The fourth override is not valid, since SQLException is not in the same
class hierarchy as IOException.

The fifth override is valid, since it does not throw any exceptions.

What is Static keyword?


In Java, the static keyword is used to create variables, methods, and
blocks that belong to the class, rather than to an instance of the class.
When a variable or method is declared as static, it is associated with the
class and not with individual objects of the class. Here are some common
uses of the static keyword:

Static variables: A static variable is a variable that belongs to the class


and is shared by all instances of the class. Static variables are declared
using the static keyword and are often used for constants or for variables
that need to be shared across instances of the class.

public class Example {

AJAY RATHOD 34
public static int count = 0;

In this example, the count variable is declared as static, so it belongs to


the Example class and is shared by all instances of the class.

Static methods: A static method is a method that belongs to the class and
can be called without creating an instance of the class. Static methods are
declared using the static keyword and are often used for utility methods
that do not depend on the state of an instance.

public class Example {

public static void printMessage(String message) {

System.out.println(message);

In this example, the printMessage() method is declared as static, so it


belongs to the Example class and can be called without creating an
instance of the class.

Static blocks: A static block is a block of code that is executed when the
class is loaded. Static blocks are used to initialize static variables or to
perform other one-time initialization tasks.

public class Example {

static {

System.out.println("Initializing Example class");

In this example, the static block is executed when the Example class is
loaded and prints a message to the console.

In summary, the static keyword is used to create variables, methods, and


blocks that belong to the class, rather than to an instance of the class.
This allows these elements to be shared by all instances of the class and
to be accessed without creating an instance of the class.

AJAY RATHOD 35
Difference between static variable and instance variables?
Static variables and instance variables are both types of variables used in
programming, but they differ in their scope and lifetime.

Static variables are declared using the "static" keyword and are shared
across all instances of a class. They are initialized only once, when the
class is loaded, and retain their value throughout the execution of the
program. Static variables are typically used to store data that is common
to all instances of a class, such as a constant or a count of objects
created.

Instance variables, on the other hand, are declared without the "static"
keyword and are unique to each instance of a class. They are initialized
when an object is created and are destroyed when the object is destroyed.
Instance variables are typically used to store data that is specific to each
instance of a class, such as the name or age of a person.

In summary, the main differences between static variables and instance


variables are:

Scope: Static variables have class scope, while instance variables have
object scope.

Lifetime: Static variables are initialized once and retain their value
throughout the execution of the program, while instance variables are
created and destroyed with the objects they belong to.

Usage: Static variables are used to store data that is common to all
instances of a class, while instance variables are used to store data that is
specific to each instance of a class.

How to make class immutable?


To make a class immutable, you need to ensure that its state cannot be
modified once it has been initialized. Here are some steps to create an
immutable class:

Declare all instance variables as private and final.

Provide only getter methods for the instance variables, and make sure
they only return the value without allowing modification.

Do not provide any setter methods or any other methods that can modify
the state of the object.

AJAY RATHOD 36
Ensure that the class cannot be subclassed by declaring it as final or
making its constructor private.

Here is an example of an immutable class:

public final class ImmutableClass {

private final String name;

private final int age;

public ImmutableClass(String name, int age) {

this.name = name;

this.age = age;

public String getName() {

return name;

public int getAge() {

return age;

Different types of access modifiers?


There are four types of access modifiers in Java:

public: The public access modifier is the most permissive access level, and
it allows access to a class, method, or variable from any other class,
regardless of whether they are in the same package or not.

protected: The protected access modifier allows access to a class, method,


or variable from within the same package, as well as from any subclass,
even if they are in a different package.

default (no modifier): If no access modifier is specified, then the class,


method, or variable has package-level access. This means that it can be

AJAY RATHOD 37
accessed from within the same package, but not from outside the
package.

private: The private access modifier is the most restrictive access level,
and it allows access to a class, method, or variable only from within the
same class. It cannot be accessed from any other class, even if they are
in the same package.

Here is an example of how access modifiers can be used:

public class MyClass {

public int publicVar;

protected int protectedVar;

int defaultVar;

private int privateVar;

public void publicMethod() {

// ...

protected void protectedMethod() {

// ...

void defaultMethod() {

// ...

private void privateMethod() {

// ...

In this example, the MyClass class has four instance variables and four
instance methods, each with a different access modifier. The publicVar
and publicMethod() can be accessed from any other class, while
protectedVar and protectedMethod() can be accessed from any subclass
and from within the same package. defaultVar and defaultMethod() can be
accessed from within the same package only, while privateVar and
privateMethod() can be accessed only from within the same class.

AJAY RATHOD 38
What is the use of protected members?
Protected members in Java are used to provide access to class members
within the same package and to subclasses of the class, even if they are
in a different package. The protected access modifier is more restrictive
than public, but less restrictive than private.

The protected access modifier is useful when you want to expose certain
methods or variables to subclasses, while still hiding them from other
classes in the same package or outside the package. For example, you
might have a superclass with some variables and methods that are not
intended to be used outside the class or package, but should be accessible
to subclasses. In this case, you can declare those variables and methods
as protected.

Here is an example of how protected members can be used:

package com.example.package1;

public class Superclass {

protected int protectedVar;

protected void protectedMethod() {

// ...

package com.example.package2;

import com.example.package1.Superclass;

public class Subclass extends Superclass {

public void someMethod() {

protectedVar = 42;

protectedMethod();

AJAY RATHOD 39
}

In this example, we have two packages, com.example.package1 and


com.example.package2. Superclass is defined in package1, and has a
protected variable protectedVar and a protected method
protectedMethod(). Subclass is defined in package2 and extends
Superclass. In the someMethod() method of Subclass, we can access
protectedVar and protectedMethod() from Superclass, even though they
are protected, because Subclass is a subclass of Superclass.

AJAY RATHOD 40

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy