Java Interview Questions
Java Classes and Objects - Theory Questions
1. What is a class and what is an object in Java?
A class is a blueprint or template that defines the properties (attributes) and behaviors (methods) that objects of that type will have. It's a logical entity that doesn't occupy memory. An object is an instance of a class - a physical entity that occupies memory. Objects have state (values of attributes), behavior (methods), and identity (unique address in memory). For example, 'Car' is a class, while 'myRedCar' is an object of the Car class.
2. Explain the main principles of Object-Oriented Programming (OOP) in Java.
Java follows four main OOP principles: Encapsulation - binding data and methods together while hiding implementation details, Inheritance - creating new classes from existing ones, Polymorphism - ability to take many forms (method overloading and overriding), and Abstraction - hiding complex implementation and showing only essential features. These principles help in creating modular, reusable, and maintainable code.
3. What are constructors in Java and what are their types?
Constructors are special methods used to initialize objects. They have the same name as the class and no return type. Types include: Default constructor - provided by Java if no constructor is defined, No-argument constructor - explicitly defined without parameters, and Parameterized constructor - with parameters to initialize objects with specific values. Constructors are called automatically when objects are created using the 'new' keyword.
4. What is the 'this' keyword and how is it used?
The 'this' keyword refers to the current object instance. It's used for: Referring to current instance variables when parameter names shadow them, Calling current class constructors using this(), and Passing current object as parameter to methods. It helps avoid naming conflicts and makes code more readable by explicitly referring to instance members.
5. Explain method overloading vs method overriding.
Method overloading occurs when multiple methods in the same class have the same name but different parameters (different type, number, or order). It's compile-time polymorphism. Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass. It must have the same name, parameters, and return type. Overriding is runtime polymorphism and requires inheritance.
6. What are access modifiers in Java and their scope?
Access modifiers control the visibility of classes, methods, and variables: private - accessible only within the same class, default (no modifier) - accessible within the same package, protected - accessible within same package and subclasses (even in different packages), and public - accessible from anywhere. These modifiers implement encapsulation by controlling access to class members.
7. What is the difference between instance variables and static variables?
Instance variables are declared in a class but outside any method, and each object gets its own copy. They represent object state. Static variables are declared with the 'static' keyword and are shared by all instances of the class. They belong to the class rather than any object. Instance variables are accessed via object reference, while static variables are accessed via class name.
8. What is the 'static' keyword and where is it used?
The 'static' keyword indicates that a member belongs to the class rather than instances. It can be used with: Variables - shared across all objects, Methods - can be called without creating objects, Blocks - executed when class is loaded, and Nested classes. Static members are loaded when the class is first loaded and can be accessed directly using the class name.
9. Explain the concept of encapsulation with examples.
Encapsulation is the mechanism of wrapping data (variables) and code (methods) together as a single unit and restricting direct access to some components. It's achieved by declaring variables as private and providing public getter and setter methods. For example, in a BankAccount class, balance would be private, and public methods like deposit() and withdraw() would control access, ensuring data validation and security.
10. What are getters and setters and why are they important?
Getters (accessor methods) are used to read private variables, and Setters (mutator methods) are used to modify private variables. They are important because they: Provide controlled access to private data, Allow validation before modifying data, Enable logging or auditing of data changes, Maintain encapsulation, and Provide flexibility to change internal implementation without affecting external code.
11. What is method signature in Java?
A method signature consists of the method name and the parameter list (type, number, and order of parameters). The return type and exceptions are not part of the signature. Method signature is used by the compiler to differentiate between methods for overloading. For example, in public void calculate(int a, double b), the signature is calculate(int, double).
12. What is the difference between instance methods and static methods?
Instance methods belong to objects and can access both instance and static variables. They are called using object reference. Static methods belong to the class and can only access static variables directly. They are called using class name. Instance methods can be overridden, while static methods can only be hidden (not truly overridden). Static methods cannot use 'this' or 'super' keywords.
13. Explain the concept of 'final' keyword with classes, methods, and variables.
The 'final' keyword provides restrictions: final variable - cannot be reassigned (constant), final method - cannot be overridden by subclasses, and final class - cannot be extended (inherited). Final variables must be initialized either at declaration or in constructor. Final parameters cannot be modified within the method. Final improves security and performance while preventing unintended modifications.
14. What are the different ways to create objects in Java?
Objects can be created using: new keyword - most common way, newInstance() method of Class class (reflection), clone() method - creates copy of existing object, Deserialization - converting byte stream to object, and Factory methods - static methods that return objects. Each method serves different purposes like dynamic object creation, object copying, or object restoration.
15. What is object initialization order in Java?
When an object is created, initialization happens in this order: Static variables and blocks of parent class (when class is loaded), Static variables and blocks of child class, Instance variables and blocks of parent class, Parent class constructor, Instance variables and blocks of child class, and Child class constructor. This ensures proper initialization hierarchy in inheritance.
16. What is the difference between composition and inheritance?
Inheritance represents an "is-a" relationship where a class inherits from another class. Composition represents a "has-a" relationship where a class contains another class as a member. Inheritance provides code reuse through extending functionality, while composition provides code reuse by containing objects. Composition is generally preferred over inheritance as it provides better flexibility, loose coupling, and avoids issues with fragile base classes.
17. What are the advantages of using objects in programming?
Advantages include: Modularity - code can be maintained independently, Reusability - objects can be reused across programs, Maintainability - easier to locate and fix bugs, Data hiding - internal implementation can be hidden, Extensibility - new features can be easily added, and Security - controlled access through methods. Objects model real-world entities making programs more intuitive and organized.
18. What is the difference between abstract classes and interfaces?
Abstract classes can have both abstract and concrete methods, can have constructors, can have instance variables, and support single inheritance. Interfaces (before Java 8) could only have abstract methods, but now can have default and static methods, cannot have constructors, can only have constants (public static final variables), and support multiple inheritance. Abstract classes represent "is-a" relationships, while interfaces represent "can-do" capabilities.
19. What is garbage collection and how does it relate to objects?
Garbage Collection is Java's automatic memory management process that deallocates objects that are no longer referenced. When objects are created with 'new', memory is allocated in heap. When objects go out of scope or references are set to null, they become eligible for garbage collection. The garbage collector runs periodically to free memory occupied by unreachable objects, preventing memory leaks and making memory management easier for developers.
20. What are the best practices for designing classes in Java?
Best practices include: Follow naming conventions (PascalCase for classes), Keep classes focused and cohesive (single responsibility), Use encapsulation properly (private fields with public getters/setters), Prefer composition over inheritance, Make classes immutable when possible, Use meaningful names for classes and methods, Keep methods short and focused, and Document classes with JavaDoc comments.