WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Basic · question 7 of 100

What is a class in Java?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

In Java, a class is a blueprint or a template that defines the characteristics and behaviors of an object. A class is a user-defined data type that encapsulates data and behavior into a single unit. It is used to create objects, which are instances of the class.

A class consists of two parts: the class declaration and the class body. The class declaration specifies the name of the class and any modifiers that apply to it (such as public or private). The class body contains the data and behavior of the class, which is defined by the class’s fields and methods.

Here’s an example Java program that demonstrates the use of a class:

public class Car {
    private String make;
    private String model;
    private int year;
    
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
    
    public String getMake() {
        return make;
    }
    
    public void setMake(String make) {
        this.make = make;
    }
    
    public String getModel() {
        return model;
    }
    
    public void setModel(String model) {
        this.model = model;
    }
    
    public int getYear() {
        return year;
    }
    
    public void setYear(int year) {
        this.year = year;
    }
}

This program defines a class called Car that represents a car. The Car class has three instance variables (make, model, and year) that represent the state of a car, and getter and setter methods for each variable that represent behaviors.

Note how the Car class encapsulates the data and behavior of a car, and how it provides methods to access and modify the state of the car. This allows objects of the Car class to be created and used to represent specific cars, and to perform actions on them.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics