- Published on
Classes and Objects
- Authors

- Name
- Iraianbu A
Table of Contents
Introduction
OOPS stands for Object Oriented Programming System. It is a programming paradigm that uses classes and objects to represent real-world entities and their interactions.Classes and objects form the foundation of OOPs.
Class
A class is blueprint or template for creating objects. It defines a set of attributes(fields) and behaviors(methods) of an object.
To define a class, we use the class keyword.
Examples
Java
public class Car{
// Attributes
private String brand;
private String model;
private int year;
// Constructor
public Car(String brand, String model, int year){
this.brand = brand;
this.model = model;
this.year = year;
}
// Methods
public void displayInfo(){
System.out.println("Brand: " + brand + ", Model: " + model +
", Year: " + year);
}
}
Output
Brand: Toyota, Model: Corolla, Year: 2020
Brand: Ford, Model: Mustang, Year: 2021
- Attributes : The class
Carhas three attributes that describes its state:brand,model, andyear. - Constructor : The constructor is a special method that initializes the object. It is called when an object is created using the
newkeyword. - Methods : The class
Carhas one method that displays the car's information.
Object
An object is an instance of a class. When you create an object, you are bringing the blueprint of the class into reality. It consists of state and behavior defined by the class, with each object holding its own copy of the data.
To create an object, we use the new keyword followed by class constructor.
Examples
Java
public class Main{
public static void main(String... args){
Car toyota = new Car("Toyota", "Corolla", 2020);
Car ford = new Car("Ford", "Mustang", 2021);
toyota.displayInfo();
ford.displayInfo();
}
}
Output
Brand: Toyota, Model: Corolla, Year: 2020
Brand: Ford, Model: Mustang, Year: 2021
- Instantiation : The
newkeyword is used to create an object, which allocates memory to the object. - Initialization : The constructor
Caris used to initialize the object. - Reference : The
toyotaandfordare references to the objects.
Access Modifiers
Access modifiers are used to restrict the access of the class members.
Java
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
public | Yes | Yes | Yes | Yes |
private | Yes | No | No | No |
default | Yes | Yes | No | No |
protected | Yes | Yes | Yes | No |
public class Car{
public String brand;
private String model;
public int price;
protected int year;
}