Java Week 3 Interview Questions and Answers
1. Can we call Constructor from child class?
Yes, constructors are called from child classes using super() keyword.
Child class constructor must call parent class constructor (explicitly or implicitly)
If not explicitly called, Java automatically calls super() (no-argument constructor)
super() must be the first statement in child constructor
java
class Parent {
public Parent() {
System.out.println("Parent constructor");
}
public Parent(String name) {
System.out.println("Parent constructor with name: " + name);
}
}
class Child extends Parent {
public Child() {
super(); // Explicit call to parent constructor
System.out.println("Child constructor");
}
public Child(String name) {
super(name); // Call parameterized parent constructor
System.out.println("Child constructor with name");
}
}
2. Program for Constructor
java
public class Student {
private String name;
private int age;
private String course;
// Default constructor
public Student() {
this.name = "Unknown";
this.age = 0;
this.course = "Not Assigned";
System.out.println("Default constructor called");
}
// Parameterized constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
this.course = "General";
System.out.println("Parameterized constructor called");
}
// Overloaded constructor
public Student(String name, int age, String course) {
this.name = name;
this.age = age;
this.course = course;
System.out.println("Overloaded constructor called");
}
// Copy constructor
public Student(Student other) {
this.name = other.name;
this.age = other.age;
this.course = other.course;
System.out.println("Copy constructor called");
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age + ", Course: " + course);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Alice", 20);
Student s3 = new Student("Bob", 22, "Computer Science");
Student s4 = new Student(s2);
s1.displayInfo();
s2.displayInfo();
s3.displayInfo();
s4.displayInfo();
}
}
3. What is public static void main?
Breakdown of public static void main(String[] args) :
public: Access modifier - JVM can access this method from anywhere
static: Method belongs to class, not instance - JVM can call without creating object
void: Return type - main method doesn't return anything
main: Method name - JVM looks for this specific method name
String[] args: Parameter - command line arguments passed as string array
java
public class MainExample {
public static void main(String[] args) {
System.out.println("Program started");
// Print command line arguments
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
4. What is Constructor Chaining?
Constructor chaining is the process of calling one constructor from another constructor within the same
class or from parent class.
Types:
1. Within same class: Using this()
2. From parent class: Using super()
java
public class Employee {
private String name;
private int id;
private double salary;
// Constructor chaining using this()
public Employee() {
this("Unknown", 0); // Calls parameterized constructor
}
public Employee(String name, int id) {
this(name, id, 0.0); // Calls three-parameter constructor
}
public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
}
5. Why constructor is not declared in interface?
Constructors cannot be declared in interfaces because:
1. Interfaces cannot be instantiated - No objects are created
2. No instance variables - Interfaces only have constants (public static final)
3. Abstract nature - Interfaces define contracts, not implementations
4. Multiple inheritance - Would create ambiguity in constructor calls
java
interface Drawable {
// This is NOT allowed
// public Drawable() { } // Compilation error
void draw(); // Abstract method
int MAX_SIZE = 100; // Constant (public static final)
}
6. Can we make constructor final?
No, constructors cannot be declared as final .
Reasons:
Constructors are not inherited, so they cannot be overridden
final keyword prevents overriding, which is meaningless for constructors
It would be redundant and cause compilation error
java
public class Test {
// This is NOT allowed
// public final Test() { } // Compilation error
public Test() { // Correct way
System.out.println("Constructor");
}
}
7. What is static?
Static is a keyword that belongs to the class rather than instances of the class.
Static elements:
Static variables (class variables)
Static methods
Static blocks
Static nested classes
Characteristics:
Loaded when class is first loaded
Shared among all instances
Can be accessed without creating objects
Memory allocated once
java
public class Counter {
private static int count = 0; // Static variable
private int instanceCount = 0; // Instance variable
static { // Static block
System.out.println("Class loaded");
}
public static void displayCount() { // Static method
System.out.println("Total count: " + count);
}
public Counter() {
count++;
instanceCount++;
}
}
8. Difference between static and non-static variables
Static Variables Non-Static Variables
Belong to class Belong to instance
Single copy shared by all objects Each object has its own copy
Memory allocated when class loads Memory allocated when object created
Accessed using class name Accessed using object reference
Also called class variables Also called instance variables
Destroyed when program ends Destroyed when object is garbage collected
java
public class Example {
static int staticVar = 0; // Static variable
int instanceVar = 0; // Instance variable
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
obj1.staticVar = 10;
obj1.instanceVar = 20;
obj2.staticVar = 30;
obj2.instanceVar = 40;
System.out.println("obj1.staticVar: " + obj1.staticVar); // 30
System.out.println("obj1.instanceVar: " + obj1.instanceVar); // 20
System.out.println("obj2.staticVar: " + obj2.staticVar); // 30
System.out.println("obj2.instanceVar: " + obj2.instanceVar); // 40
}
}
9. Why main method is static?
Main method is static because:
1. JVM needs to call it without creating object - Program entry point
2. No instance required - JVM doesn't know which constructor to call
3. Class loading - Static methods are available as soon as class is loaded
4. Memory efficiency - No need to create unnecessary objects
java
public class MainStatic {
public static void main(String[] args) {
// JVM calls this without creating MainStatic object
System.out.println("Program starts here");
}
// If main was non-static (hypothetically):
// JVM would need: MainStatic obj = new MainStatic(); obj.main(args);
// But which constructor to use? This creates confusion.
}
10. What's use of private constructor in singleton class?
Private constructor in Singleton pattern:
1. Prevents external instantiation - Only one instance possible
2. Controls object creation - Class controls when and how object is created
3. Ensures single instance - Core requirement of Singleton pattern
java
public class Singleton {
private static Singleton instance;
// Private constructor prevents external instantiation
private Singleton() {
System.out.println("Singleton instance created");
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
System.out.println("Doing something...");
}
}
// Usage
class Test {
public static void main(String[] args) {
// Singleton s = new Singleton(); // Compilation error
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); // true - same instance
}
}
11. Class having constructor, static block and static method - execution flow
Execution Order:
1. Static blocks - When class is first loaded
2. Constructor - When object is created
3. Static methods - When explicitly called
java
public class ExecutionFlow {
static {
System.out.println("1. Static block executed");
}
{
System.out.println("3. Instance block executed");
}
public ExecutionFlow() {
System.out.println("4. Constructor executed");
}
public static void staticMethod() {
System.out.println("5. Static method executed");
}
public static void main(String[] args) {
System.out.println("2. Main method starts");
ExecutionFlow obj1 = new ExecutionFlow();
ExecutionFlow obj2 = new ExecutionFlow();
staticMethod();
}
}
// Output:
// 1. Static block executed
// 2. Main method starts
// 3. Instance block executed
// 4. Constructor executed
// 3. Instance block executed
// 4. Constructor executed
// 5. Static method executed
12. Constructor in Java
Constructor is a special method used to initialize objects.
Characteristics:
Same name as class
No return type (not even void)
Called automatically when object is created
Can be overloaded
Cannot be inherited
Cannot be abstract, static, or final
java
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods
public String getName() { return name; }
public int getAge() { return age; }
}
13. Constructor Chaining (Detailed)
Constructor chaining allows calling one constructor from another.
java
public class Vehicle {
private String brand;
private String model;
private int year;
private String color;
// Constructor chaining with this()
public Vehicle() {
this("Unknown", "Unknown", 2023, "White");
}
public Vehicle(String brand) {
this(brand, "Unknown", 2023, "White");
}
public Vehicle(String brand, String model) {
this(brand, model, 2023, "White");
}
public Vehicle(String brand, String model, int year, String color) {
this.brand = brand;
this.model = model;
this.year = year;
this.color = color;
}
}
14. Advantages of static
1. Memory efficiency - Single copy shared by all instances
2. No object required - Can access without creating objects
3. Early initialization - Loaded when class is loaded
4. Utility methods - Math.max(), Arrays.sort()
5. Constants - Math.PI, Integer.MAX_VALUE
6. Performance - No overhead of object creation
java
public class MathUtils {
public static final double PI = 3.14159;
public static int add(int a, int b) {
return a + b;
}
public static int max(int a, int b) {
return (a > b) ? a : b;
}
}
// Usage without creating object
int result = MathUtils.add(5, 3);
int maximum = MathUtils.max(10, 20);
15. What is constructor? Types of constructor
Constructor is a special method that initializes objects when they are created.
Types of Constructors:
1. Default Constructor
java
public class Student {
public Student() { // Default constructor
System.out.println("Default constructor");
}
}
2. Parameterized Constructor
java
public class Student {
private String name;
public Student(String name) { // Parameterized constructor
this.name = name;
}
}
3. Copy Constructor
java
public class Student {
private String name;
public Student(Student other) { // Copy constructor
this.name = other.name;
}
}
16. Explain the access specifiers
Access Specifiers control visibility of classes, methods, and variables.
Modifier Same Class Same Package Subclass Different Package
private ✓ ✗ ✗ ✗
default ✓ ✓ ✗ ✗
protected ✓ ✓ ✓ ✗
public ✓ ✓ ✓ ✓
java
public class AccessExample {
private int privateVar = 1; // Only within same class
int defaultVar = 2; // Within same package
protected int protectedVar = 3; // Within package + subclasses
public int publicVar = 4; // Everywhere
private void privateMethod() { }
void defaultMethod() { }
protected void protectedMethod() { }
public void publicMethod() { }
}
17. Where does static is applicable?
Static can be applied to:
1. Variables - Class-level variables
2. Methods - Utility methods
3. Blocks - Initialization blocks
4. Nested Classes - Inner classes
Static CANNOT be applied to:
Top-level classes (only nested)
Constructors
Instance variables (contradiction)
Abstract methods
java
public class StaticExample {
static int staticVar; // ✓ Static variable
static void staticMethod() { } // ✓ Static method
static { // ✓ Static block
staticVar = 10;
}
static class StaticNestedClass { // ✓ Static nested class
// static Constructor() { } // ✗ NOT allowed
// static abstract void method(); // ✗ NOT allowed
}
18. Can we call non-static method from static method?
No, we cannot directly call non-static methods from static methods.
Reason: Static methods belong to class, non-static methods belong to instances.
Solution: Create object first, then call non-static method.
java
public class MethodCall {
public void nonStaticMethod() {
System.out.println("Non-static method");
}
public static void staticMethod() {
// nonStaticMethod(); // ✗ Compilation error
// ✓ Correct way - create object first
MethodCall obj = new MethodCall();
obj.nonStaticMethod();
}
public static void main(String[] args) {
staticMethod();
}
}
19. What is single copy storage?
Single copy storage refers to static variables that have only one copy shared among all instances of a
class.
Characteristics:
One memory location for all objects
Changes reflect across all instances
Memory allocated in Method Area
Also called "class variables"
java
public class Counter {
static int count = 0; // Single copy storage
int instanceCount = 0; // Multiple copies (one per object)
public Counter() {
count++; // Shared counter
instanceCount++; // Individual counter
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println("Static count: " + Counter.count); // 3
System.out.println("c1 instance: " + c1.instanceCount); // 1
System.out.println("c2 instance: " + c2.instanceCount); // 1
System.out.println("c3 instance: " + c3.instanceCount); // 1
}
}
20. Static keyword in Java
Static means "belonging to the class rather than any instance."
Key Points:
Loaded during class loading
Shared by all instances
Can be accessed without objects
Memory allocated once
Cannot access non-static members directly
java
public class StaticDemo {
static String className = "StaticDemo";
String instanceName;
static {
System.out.println("Static block: Class loading");
}
public StaticDemo(String name) {
this.instanceName = name;
System.out.println("Constructor: " + name);
}
static void staticMethod() {
System.out.println("Static method called");
// System.out.println(instanceName); // ✗ Cannot access
}
void instanceMethod() {
System.out.println("Instance method: " + instanceName);
System.out.println("Can access static: " + className); // ✓ Can access
}
}
21. Can we make constructor as final? Reason
No, constructors cannot be declared as final .
Reasons:
1. Constructors are not inherited - They belong to specific class
2. Cannot be overridden - Each class has its own constructors
3. Final prevents overriding - Meaningless for constructors
4. Compilation error - Java compiler rejects it
java
public class FinalConstructor {
// public final FinalConstructor() { } // ✗ Compilation error
public FinalConstructor() { // ✓ Correct
System.out.println("Constructor");
}
// final methods can exist
public final void finalMethod() {
System.out.println("Final method - cannot be overridden");
}
}
22. Constructor chaining using this keyword
Constructor chaining with this() calls another constructor in the same class.
Rules:
this() must be first statement
Cannot be used in same constructor (recursion)
Creates a chain of constructor calls
java
public class Student {
private String name;
private int age;
private String course;
private double gpa;
// Default constructor
public Student() {
this("Unknown"); // Chain to single parameter constructor
}
// Single parameter constructor
public Student(String name) {
this(name, 18); // Chain to two parameter constructor
}
// Two parameter constructor
public Student(String name, int age) {
this(name, age, "General"); // Chain to three parameter constructor
}
// Three parameter constructor
public Student(String name, int age, String course) {
this(name, age, course, 0.0); // Chain to four parameter constructor
}
// Master constructor - all initialization happens here
public Student(String name, int age, String course, double gpa) {
this.name = name;
this.age = age;
this.course = course;
this.gpa = gpa;
System.out.println("Master constructor called");
}
public void display() {
System.out.println(name + ", " + age + ", " + course + ", " + gpa);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Alice");
Student s3 = new Student("Bob", 20);
Student s4 = new Student("Charlie", 21, "CS");
s1.display();
s2.display();
s3.display();
s4.display();
}
}
23. Can we override static method?
No, static methods cannot be overridden. They can be hidden or redefined.
Reason:
Method overriding is runtime polymorphism
Static methods are resolved at compile time
Static methods belong to class, not instances
java
class Parent {
public static void staticMethod() {
System.out.println("Parent static method");
}
public void instanceMethod() {
System.out.println("Parent instance method");
}
}
class Child extends Parent {
// This is method hiding, not overriding
public static void staticMethod() {
System.out.println("Child static method");
}
// This is method overriding
@Override
public void instanceMethod() {
System.out.println("Child instance method");
}
}
public class MethodTest {
public static void main(String[] args) {
Parent p = new Child();
p.staticMethod(); // "Parent static method" - Compile time binding
p.instanceMethod(); // "Child instance method" - Runtime binding
Child.staticMethod(); // "Child static method" - Direct call
}
}
24. Advantages of Inner Class
Inner classes provide several benefits:
1. Logical grouping - Groups related classes together
2. Encapsulation - Can access private members of outer class
3. Readability - Code is closer to where it's used
4. Maintainability - Helper classes stay with main class
Types of Inner Classes:
java
public class OuterClass {
private String outerField = "Outer field";
private static String staticField = "Static field";
// 1. Member Inner Class
class MemberInner {
public void display() {
System.out.println("Accessing: " + outerField);
}
}
// 2. Static Nested Class
static class StaticNested {
public void display() {
System.out.println("Accessing: " + staticField);
// System.out.println(outerField); // ✗ Cannot access non-static
}
}
// 3. Method Local Inner Class
public void method() {
final String localVar = "Local variable";
class LocalInner {
public void display() {
System.out.println("Accessing: " + outerField);
System.out.println("Accessing: " + localVar);
}
}
LocalInner local = new LocalInner();
local.display();
}
// 4. Anonymous Inner Class
public void anonymousExample() {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Anonymous inner class");
}
};
r.run();
}
}
25. All Access Specifiers
Private
Scope: Within same class only
Use: Sensitive data, internal methods
java
class PrivateExample {
private int data = 10;
private void privateMethod() {
System.out.println("Private method");
}
}
Default (Package-Private)
Scope: Within same package
Use: Package-level utilities
java
class DefaultExample {
int data = 10; // Default access
void defaultMethod() {
System.out.println("Default method");
}
}
Protected
Scope: Same package + subclasses
Use: Inheritance scenarios
java
class ProtectedExample {
protected int data = 10;
protected void protectedMethod() {
System.out.println("Protected method");
}
}
Public
Scope: Everywhere
Use: Public APIs, main methods
java
public class PublicExample {
public int data = 10;
public void publicMethod() {
System.out.println("Public method");
}
}
26. Static in Java (Comprehensive)
Static is a non-access modifier that creates class-level members.
Static Variables
java
class Counter {
static int count = 0; // Shared by all instances
Counter() {
count++;
}
}
Static Methods
java
class MathUtils {
static int add(int a, int b) {
return a + b;
}
}
Static Blocks
java
class StaticBlock {
static {
System.out.println("Static block executed");
// Initialization code
}
}
Static Import
java
import static java.lang.Math.*;
public class StaticImportExample {
public static void main(String[] args) {
System.out.println(PI); // Math.PI
System.out.println(max(5, 3)); // Math.max(5, 3)
}
}
27. Protected and Private Access Modifier Use
Protected Access Modifier
Use Cases:
Inheritance scenarios - Allow subclass access
Framework development - Protected APIs for extension
Template method pattern - Subclasses implement specific parts
java
// Base class
class Animal {
protected String name;
protected int age;
protected void makeSound() {
System.out.println("Animal makes sound");
}
// Template method
public final void dailyRoutine() {
wakeUp();
makeSound(); // Protected - subclasses can override
sleep();
}
private void wakeUp() {
System.out.println("Animal wakes up");
}
private void sleep() {
System.out.println("Animal sleeps");
}
}
// Subclass can access protected members
class Dog extends Animal {
public Dog(String name, int age) {
this.name = name; // ✓ Protected access
this.age = age; // ✓ Protected access
}
@Override
protected void makeSound() {
System.out.println(name + " barks");
}
}
Private Access Modifier
Use Cases:
Data hiding - Protect sensitive information
Implementation details - Hide internal logic
Controlled access - Provide public methods for access
java
class BankAccount {
private double balance; // Private - cannot be accessed directly
private String accountNumber; // Private - sensitive information
private int pin; // Private - security critical
public BankAccount(String accountNumber, int pin) {
this.accountNumber = accountNumber;
this.pin = pin;
this.balance = 0.0;
}
// Public methods provide controlled access
public boolean deposit(double amount) {
if (isValidAmount(amount)) {
balance += amount;
return true;
}
return false;
}
public boolean withdraw(double amount, int enteredPin) {
if (validatePin(enteredPin) && isValidAmount(amount) && hasSufficientBalance(amount)) {
balance -= amount;
return true;
}
return false;
}
public double getBalance(int enteredPin) {
return validatePin(enteredPin) ? balance : -1;
}
// Private helper methods - implementation details
private boolean validatePin(int enteredPin) {
return this.pin == enteredPin;
}
private boolean isValidAmount(double amount) {
return amount > 0;
}
private boolean hasSufficientBalance(double amount) {
return balance >= amount;
}
}
Comparison Example
java
package com.example.bank;
class Account {
private String accountId; // Only within Account class
String bankName; // Within com.example.bank package
protected double balance; // Package + subclasses
public String holderName; // Everywhere
private void validateAccount() { } // Internal validation
void processTransaction() { } // Package utilities
protected void updateBalance() { } // For specialized account types
public void displayInfo() { } // Public API
}
// Same package
class AccountManager {
public void manage() {
Account acc = new Account();
// acc.accountId = "123"; // ✗ Private
acc.bankName = "ABC Bank"; // ✓ Default
acc.balance = 1000.0; // ✓ Protected
acc.holderName = "John"; // ✓ Public
}
}
// Different package - subclass
package com.example.savings;
import com.example.bank.Account;
class SavingsAccount extends Account {
public void addInterest() {
// accountId = "123"; // ✗ Private
// bankName = "ABC"; // ✗ Default (different package)
balance += balance * 0.05; // ✓ Protected (inheritance)
holderName = "Updated Name"; // ✓ Public
}
}
Summary
This comprehensive guide covers all essential Java concepts related to constructors, static keyword,
access specifiers, and their practical applications. These concepts form the foundation of Java
programming and are frequently tested in technical interviews.
Key Takeaways:
Constructors initialize objects and support chaining
Static members belong to class, not instances
Access specifiers control visibility and encapsulation
Understanding execution flow is crucial for debugging
Inner classes provide powerful code organization capabilities
Practice these concepts with code examples to master Java fundamentals!