In Object-Oriented Programming language, Classes and Objects are the essential building blocks. The “class” keyword is used to declare the class followed by a reference name.
Syntax:
class Car {
//class body
}
Classes are known as the blueprint of object creation. Classes that are defined by the user are the implementation of real-life scenarios. A class defines the state and behavior of an object.State – State is either the property or variables declared within a class.
Behaviour– Behaviour denotes functions or methods that are created inside a class.
In the following example of a Car class, variables declared inside the class are the properties, and methods that define the start and acceleration of the class Car are the behaviour.
public class Car {
private String doors;
private String engine;
private String drivers;
public int speed;
}In the following example, the class Car has some properties like doors, engine, speed, and driver. We will use again the properties of the Car class in another “Hello” class.
An object is used to instantiate its state in fields that are already declared in class and exposes its behaviour through functions. To instantiate the “Car” class, it is needed to create an object of the “Car” class in the “Hello” class.
new Car(); is the object of the Car class which is referenced by the obj variable.public class Car {
private String doors;
private String engine;
private String drivers;
public int speed;
}
public class Hello {
public static void main(String[] args) {
Car obj = new Car();
obj.speed=1;
System.out.println(obj.speed);
}
}Output: 1
Classes-Getters and Setters:
Getter and setter methods are used to fetch and set (update) the value of the private variable. When you hide the implementation of the object of the class from the outer world, you declare them as private. The private members of the class cannot access from outside the class, so the getter and setter methods can be used to retrieve and update the values of private members.
In the following example, we have declared some private variables inside the class. We will write getter and setter methods for the variables.
The setter method is a parameterized method with the return type as void, which is used to update the value. The getter method has a return type which will be the same as the data type of the private variable. The following Java program has the setter and getter for the variable “speed” of the Car class.public class Car {
private String doors;
private String engine;
private String drivers;
private int speed;
public void setspeed(int speed) {
this.speed=speed;
}
public int getspeed() {
return speed;
}
}To access the properties (variable) and functionalities (methods) of “car” in another class, we have to create the object of the Car class.
public class Hello{
public static void main(String[] args) {
Car car = new Car ();
car.setspeed (10);
System.out.println (car.getspeed());
}
}
Output: 10