Java Docs
Java Documentation
Java Classes and Objects
Java is an object-oriented programming language. Objects represent entities that have both state and behavior. For example, a bicycle is an object with:
- States: idle, first gear, etc.
- Behaviors: braking, accelerating, etc.
Java Class
A class is a blueprint for creating objects. It defines the state (fields) and behavior Methods of the objects.
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}Creating Objects
An object is an instance of a class. You can create multiple objects from a single class using the new keyword.
Bicycle sportsBicycle = new Bicycle(); Bicycle touringBicycle = new Bicycle();
Accessing Members
Use the object name with the . operator to access fields and methods.
sportsBicycle.gear; sportsBicycle.braking();
Example 1: Class and Objects
class Lamp {
boolean isOn;
void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);
}
void turnOff() {
isOn = false;
System.out.println("Light on? " + isOn);
}
}
public class Main {
public static void main(String[] args) {
Lamp led = new Lamp();
Lamp halogen = new Lamp();
led.turnOn();
halogen.turnOff();
}
}Output
Output:Light on? trueLight on? false
Example 2: Objects Inside the Same Class
class Lamp {
boolean isOn;
void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);
}
public static void main(String[] args) {
Lamp led = new Lamp();
led.turnOn();
}
}Output
Output:Light on? true