Consider the following Java class that uses encapsulation. What will be printed when the main method runs?
class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } public class Main { public static void main(String[] args) { Person p = new Person(); p.setName("Alice"); System.out.println(p.getName()); } }
Think about how private fields are accessed through public methods.
The name field is private but accessed via public setter and getter methods. The setName method sets the name to "Alice", so getName returns "Alice".
Look at this Java code with inheritance and method overriding. What will it print?
class Animal { public String sound() { return "Some sound"; } } class Dog extends Animal { @Override public String sound() { return "Bark"; } } public class Main { public static void main(String[] args) { Animal a = new Dog(); System.out.println(a.sound()); } }
Remember how method overriding works with polymorphism.
The variable a is of type Animal but refers to a Dog object. The overridden sound method in Dog is called, printing "Bark".
Analyze this Java code using an abstract class. What will be printed when the main method runs?
abstract class Vehicle { abstract void start(); void stop() { System.out.println("Vehicle stopped"); } } class Car extends Vehicle { @Override void start() { System.out.println("Car started"); } } public class Main { public static void main(String[] args) { Vehicle v = new Car(); v.start(); v.stop(); } }
Think about how abstract methods are implemented in subclasses.
The abstract method start is implemented in Car. Calling start on v calls the Car version, printing "Car started". The stop method is concrete in Vehicle, so it prints "Vehicle stopped".
Consider this Java code where a class implements an interface but misses a method. What error occurs?
interface Flyer { void fly(); } class Bird implements Flyer { // Missing fly() method implementation } public class Main { public static void main(String[] args) { Bird b = new Bird(); b.fly(); } }
Interfaces require all methods to be implemented unless the class is abstract.
The class Bird does not implement the fly() method from Flyer. Since Bird is not abstract, this causes a compilation error.
Given this Java code snippet, which core OOP principle does it best illustrate?
class Shape {
void draw() {
System.out.println("Drawing shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing circle");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing square");
}
}
public class Main {
public static void main(String[] args) {
Shape s1 = new Circle();
Shape s2 = new Square();
s1.draw();
s2.draw();
}
}Think about how the same method call behaves differently depending on the object type.
The code shows polymorphism because the draw() method behaves differently for Circle and Square objects even though they are referenced as Shape.