Skip to content
CodeKruPro

Your language · Java

Classes and objects (OOP)

Classes, objects, constructors and the four pillars with real examples.

Learn: Classes and objects in Java: the four pillars9 minute read

Object-oriented programming (OOP) means building a program from objects that hold data and the code that works on it. "Explain OOP with examples" is the most common Java question for testers, and the follow-up is nearly always "where did you use it in your framework?". So learn each idea together with a piece of test code, such as a page object (a class that stands for one page of the application you test and holds the steps to use it).

Step 1: classes, objects and constructors

A class is a blueprint: fields (variables inside the class) hold the state and methods hold the behaviour. An object is one instance of a class, made with new. A constructor sets up a new object; it has the class name and no return type. If you write no constructor, the compiler adds an empty one with no arguments, but once you write any constructor it does not. One constructor can call another with this(...), or the parent's with super(...), and that call must be the first statement. The parent part of an object is always built first.

Step 2: the four pillars

An abstract BasePage class with LoginPage and CartPage extending it, with one line each on how the design shows encapsulation, inheritance, abstraction and polymorphism.
One small page-object design shows all four pillars.
  • Encapsulation means keeping fields private and exposing methods that protect the object's rules. A page object hides its locators (the rules that tell Selenium how to find an element on the page) and offers login(user, password).
  • Inheritance lets a subclass (a class that extends another) reuse a parent class (also called the superclass) with extends. Page classes extend a BasePage that holds the driver (the Selenium object that controls the browser) and shared helpers. A Java class has exactly one parent class.
  • Polymorphism means one reference type (the type written on the variable) with many behaviours. In WebDriver driver = new ChromeDriver(); the test code works the same with any browser.
  • Abstraction means showing what an object does and hiding how. Interfaces and abstract classes describe the "what"; subclasses supply the "how".
import java.util.*;

abstract class BasePage {
    protected final String name;
    BasePage(String name) { this.name = name; }
    abstract boolean isLoaded();                       // each page decides
    String describe() { return name + " loaded=" + isLoaded(); }
}

class LoginPage extends BasePage {
    private final String usernameField = "#username";   // encapsulated locator
    LoginPage() { super("Login"); }
    @Override boolean isLoaded() { return true; }
    String usernameLocator() { return usernameField; }
}

class CartPage extends BasePage {
    private int items;
    CartPage(int items) { super("Cart"); this.items = items; }
    @Override boolean isLoaded() { return items >= 0; }
    @Override String describe() { return super.describe() + " items=" + items; }
}

public class Main {
    public static void main(String[] args) {
        List<BasePage> pages = List.of(new LoginPage(), new CartPage(2));
        for (BasePage page : pages) {
            System.out.println(page.describe());          // run-time choice
        }
        BasePage p = new LoginPage();
        System.out.println(p instanceof LoginPage lp ? lp.usernameLocator() : "?");
    }
}
Login loaded=true
Cart loaded=true items=2
#username

The loop calls describe() on a BasePage variable, but the cart page runs its own version. That is run-time polymorphism.

Step 3: overriding and overloading

Overriding means a subclass gives its own version of a parent method with the same name and parameters; Java picks it at run time from the real object. Overloading means several methods share a name but take different parameters; the compiler picks one from the declared types. The rules for an override:

  • The return type stays the same or becomes a subtype (a class that extends the original type).
  • Access can stay the same or widen, never narrow.
  • Checked exceptions (errors the compiler forces you to handle; see Exceptions) can stay, narrow or disappear, never broaden.
  • static methods (they belong to the class) are hidden, private methods are not inherited, and final methods cannot be overridden. Hidden means a subclass can declare the same static method, but it does not replace the parent's.
  • Fields are never polymorphic: parentRef.field reads the field of the declared type.

Put @Override on every override so the compiler catches a typo in the name.

Step 4: abstract class or interface?

An abstract class cannot be created with new. It can hold fields, constructors and finished methods, and a class extends only one. An interface is a contract: its fields are constants, and its methods are abstract unless marked default, static or private. A class can implement many interfaces. Use an interface for a capability shared by unrelated classes, such as WebDriver or TakesScreenshot. Use an abstract class when related classes share state and code, such as BasePage. If two interfaces give a class the same default method, the class must override it. This is Java's answer to the diamond problem: a class would inherit one method from two parents and Java could not tell which one to use (the practice questions in this topic cover the full rules).

Inheritance is an IS-A link: a LoginPage is a BasePage. Composition is HAS-A: a page has a driver. Prefer composition unless the IS-A sentence is really true. A record, such as record User(String name, String role) {}, gives an immutable data class (its values cannot change after creation) with equals, hashCode and toString written for you, which suits test data.

How to answer in an interview

Take the pillars one at a time and give each a one-line definition plus one place in your framework: "Inheritance: every page extends BasePage, which holds the driver. Encapsulation: locators are private. Polymorphism: we declare WebDriver and a factory (a method that creates and returns the right object) returns Chrome or Firefox. Abstraction: BasePage makes each page implement isLoaded()." Mention only what you can open and show.

Common mistakes

  • Mixing up overloading and overriding, or calling a static method "overridden".
  • Defining abstraction and encapsulation the same way. Abstraction hides how something works; encapsulation protects data.
  • Making a test class extend a page class just to reuse its methods.
  • Expecting parentRef.field to read the child's field.

Recap

A class is a blueprint and an object is one instance. Encapsulation protects data, inheritance reuses code, polymorphism lets one reference run many versions, and abstraction hides how things work. Overriding is chosen at run time and overloading at compile time. Use interfaces for contracts and abstract classes for shared code.

17 questions0/17 solved

StatusQuestionDifficultyAsked in
Not startedOverloading or overriding?EasyAsked in: Accenture, Capgemini, Infosys +2
Not startedThe four OOP pillars with an example of eachEasy-MediumAsked in: Accenture, Amazon, Capgemini +7
Pro+Method overloading versus method overridingEasy-MediumAsked in: Accenture, Capgemini, Infosys +2
Pro+Abstract class vs interface: when to use eachMediumAsked in: Accenture, Capgemini, Infosys +2
Pro+Abstraction versus encapsulationMediumAsked in: Capgemini, Coupa, HCLTech
Pro+Rules for interfaces in Java 21MediumAsked in: Accenture, Capgemini, Infosys +2
Pro+Multiple inheritance and the diamond problemMediumAsked in: Accenture, TCS
Pro+Compile-time vs run-time polymorphismMediumAsked in: Accenture, Capgemini, Cognizant +3
Pro+Constructors: types, overloading, chaining and super()MediumAsked in: Accenture, Capgemini, Infosys +2
Pro+this versus superEasy-MediumAsked in: Accenture, Capgemini, Infosys +1
Pro+Can static, private or final methods be overridden? Can main be overloaded?MediumAsked in: Accenture, Capgemini, Infosys +1
Pro+Parent reference, child object: what runs?MediumAsked in: Accenture, Capgemini, Cognizant +3
Pro+IS-A versus HAS-A; types of inheritanceEasy-MediumAsked in: TCS, Wipro
Pro+Private constructors and immutable classesMediumAsked in: Accenture, Infosys
Pro+Where have you used OOP in your automation framework?MediumAsked in: Accenture, Capgemini, Salesforce +2
Pro+Count how many objects of a class were createdEasy-MediumAsked in: Infosys
Pro+Order of constructor calls with this() and super()MediumAsked in: Accenture, Capgemini, Infosys +2
Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan