Skip to content
Laviyx Learn

Try

Java Object-Oriented Programming Practice

Practise Java classes, constructors, encapsulation, inheritance, polymorphism, interfaces, records and enums.

Intermediate6 problemsUpdated

Review first: Classes and Objects, Constructors, Encapsulation, Inheritance, Polymorphism, Abstract Classes, Interfaces, Records and Enums

  1. 1.An encapsulated bank account

    Intermediate

    Write a class BankAccount with a private balance, deposit(double), boolean withdraw(double) (refusing amounts above the balance) and getBalance(). Deposit 1000, withdraw 300, try to withdraw 5000, and print the results.

    Show hint

    Keep the field private, so it can only change through the methods that enforce the rules.

    Show solution
    Java
    class BankAccount {
        private double balance;
    
        void deposit(double amount) {
            if (amount > 0) balance += amount;
        }
    
        boolean withdraw(double amount) {
            if (amount <= 0 || amount > balance) return false;
            balance -= amount;
            return true;
        }
    
        double getBalance() {
            return balance;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            BankAccount acc = new BankAccount();
            acc.deposit(1000);
            System.out.println(acc.withdraw(300) + " " + acc.withdraw(5000));
            System.out.println(acc.getBalance());
        }
    }
    Output
    true false
    700.0
  2. 2.Validate in the constructor

    Intermediate

    Write a class Rectangle whose constructor throws IllegalArgumentException for a non-positive width or height, with area() and toString() returning Rectangle[4.0 x 2.5]. Create a valid rectangle, then try a 0 × 3 one.

    Show hint

    Check the arguments before assigning the final fields.

    Show solution
    Java
    class Rectangle {
        private final double width;
        private final double height;
    
        Rectangle(double width, double height) {
            if (width <= 0 || height <= 0) {
                throw new IllegalArgumentException("sides must be positive");
            }
            this.width = width;
            this.height = height;
        }
    
        double area() {
            return width * height;
        }
    
        @Override
        public String toString() {
            return "Rectangle[" + width + " x " + height + "]";
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Rectangle r = new Rectangle(4, 2.5);
            System.out.println(r + " area " + r.area());
            try {
                new Rectangle(0, 3);
            } catch (IllegalArgumentException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }
    Output
    Rectangle[4.0 x 2.5] area 10.0
    Error: sides must be positive
  3. 3.Inheritance and overriding

    Intermediate

    Create a class Employee with a name, a salary and double pay(). Extend it with Manager, which adds a bonus. Store an employee (50000) and a manager (80000 + 15000 bonus) in a List<Employee> and print each name and pay.

    Show hint

    Call super(name, salary) in the Manager constructor, and super.pay() inside the overriding method.

    Show solution
    Java
    import java.util.List;
    
    class Employee {
        private final String name;
        private final double salary;
    
        Employee(String name, double salary) {
            this.name = name;
            this.salary = salary;
        }
    
        String getName() { return name; }
    
        double pay() { return salary; }
    }
    
    class Manager extends Employee {
        private final double bonus;
    
        Manager(String name, double salary, double bonus) {
            super(name, salary);
            this.bonus = bonus;
        }
    
        @Override
        double pay() { return super.pay() + bonus; }
    }
    
    public class Main {
        public static void main(String[] args) {
            List<Employee> staff = List.of(new Employee("Ravi", 50000), new Manager("Meera", 80000, 15000));
            for (Employee e : staff) {
                System.out.println(e.getName() + ": " + e.pay());
            }
        }
    }
    Output
    Ravi: 50000.0
    Meera: 95000.0
  4. 4.Polymorphism with an interface

    Intermediate

    Define an interface Shape with double area() and String name(). Implement Circle and Square, put a circle of radius 1 and a square of side 3 in a list, and print each name with its area (2 decimals) and the total.

    Show hint

    The loop calls area() and name() through the interface; each class supplies its own version.

    Show solution
    Java
    import java.util.List;
    
    interface Shape {
        double area();
        String name();
    }
    
    class Circle implements Shape {
        private final double r;
        Circle(double r) { this.r = r; }
        public double area() { return Math.PI * r * r; }
        public String name() { return "Circle"; }
    }
    
    class Square implements Shape {
        private final double s;
        Square(double s) { this.s = s; }
        public double area() { return s * s; }
        public String name() { return "Square"; }
    }
    
    public class Main {
        public static void main(String[] args) {
            List<Shape> shapes = List.of(new Circle(1), new Square(3));
            double total = 0;
            for (Shape s : shapes) {
                System.out.printf("%s: %.2f%n", s.name(), s.area());
                total += s.area();
            }
            System.out.printf("Total: %.2f%n", total);
        }
    }
    Output
    Circle: 3.14
    Square: 9.00
    Total: 12.14
  5. 5.Records compare by value

    Intermediate

    Define record Point(int x, int y). Create two points with the same coordinates and print them, whether they are equals, and the size of a HashSet after adding both.

    Show hint

    Records generate equals, hashCode and toString from their components.

    Show solution
    Java
    import java.util.HashSet;
    import java.util.Set;
    
    record Point(int x, int y) {}
    
    public class Main {
        public static void main(String[] args) {
            Point a = new Point(3, 4);
            Point b = new Point(3, 4);
            System.out.println(a + " " + a.equals(b) + " " + (a == b));
    
            Set<Point> set = new HashSet<>();
            set.add(a);
            set.add(b);
            System.out.println(set.size());
        }
    }
    Output
    Point[x=3, y=4] true false
    1
  6. 6.An enum with data

    Intermediate

    Define enum Size { SMALL(100), MEDIUM(150), LARGE(200) } with a price() method, and print every size with its price, then the total for 2 LARGE and 1 SMALL.

    Show hint

    Give the enum a private final int price field and a constructor. Size.values() lists all constants.

    Show solution
    Java
    enum Size {
        SMALL(100), MEDIUM(150), LARGE(200);
    
        private final int price;
    
        Size(int price) {
            this.price = price;
        }
    
        int price() {
            return price;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            for (Size s : Size.values()) {
                System.out.println(s + " " + s.price());
            }
            System.out.println("Total: " + (2 * Size.LARGE.price() + Size.SMALL.price()));
        }
    }
    Output
    SMALL 100
    MEDIUM 150
    LARGE 200
    Total: 500