Java ยท Chapter 22 of 42
Java OOP: Classes and Objects
Object-Oriented Programming (OOP) organizes code around objects, which are instances of classes. A class is a blueprint defining fields (data) and methods (behavior); an object is a concrete instance created from that blueprint.
Java is a fundamentally object-oriented language โ nearly everything, aside from primitives, is an object.
Syntax
class ClassName {
type field;
void method() { }
}
ClassName obj = new ClassName();Defining a class
A class groups related fields and methods together. Fields represent an object's state, methods represent its behavior.
Creating objects
The `new` keyword creates an object (an instance) from a class, allocating memory and calling a constructor to initialize it.
Example 1 (java)
class Car {
String brand = "Toyota";
void drive() {
System.out.println(brand + " is driving");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.drive();
}
}Output
Toyota is drivingCar is a class; myCar is an object created from it using new.
Key points
- A class is a blueprint; an object is an instance of it.
- Fields store an object's state, methods define its behavior.
- new creates a new object in memory.
- OOP models real-world entities as objects.
๐ก Note: Almost everything in Java besides the 8 primitive types is treated as an object.
