In Java, classes and objects form the foundation of object-oriented programming (OOP). Understanding how to use classes and objects is essential for creating robust and reusable Java applications. In this guide, we will cover the basics of classes and objects, how to define them, and how to interact with them in Java.
In Java, everything is associated with a class, and all code is written inside classes.
To define a class in Java, you use the class
keyword, followed by the name of the class. By convention, class names start with an uppercase letter.
public class ClassName {
// Fields (variables)
// Methods
// Constructors
}
public class Car {
// Fields
String brand;
String model;
int year;
// Method
void startEngine() {
System.out.println("Engine started");
}
}
In this example, the Car
class has three fields: brand
, model
, and year
. It also has a method startEngine()
that simulates starting the car's engine.
Once you have a class defined, you can create objects from that class. Creating an object is called instantiating a class.
ClassName objectName = new ClassName();
ClassName
: The name of the class.objectName
: The name of the object.new
: The keyword used to create a new instance of the class.Car
Class
public class Main {
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car();
// Accessing fields of the object
myCar.brand = "Toyota";
myCar.model = "Camry";
myCar.year = 2020;
// Calling method on the object
myCar.startEngine();
// Output object details
System.out.println("Car brand: " + myCar.brand);
System.out.println("Car model: " + myCar.model);
System.out.println("Car year: " + myCar.year);
}
}
Output:
Engine started
Car brand: Toyota
Car model: Camry
Car year: 2020
In this example, we created an object myCar
of the Car
class and set its fields. We also called the startEngine()
method to simulate starting the car's engine.
Fields represent the state or properties of an object. They are declared inside the class but outside the methods.
Example:
String brand;
int speed;
Methods define the behavior of the objects. You can use methods to manipulate the data (fields) or perform actions.
Example:
void accelerate() {
speed += 10;
System.out.println("Accelerated to " + speed + " km/h");
}
Constructors are special methods used to initialize objects when they are created. Constructors have the same name as the class and are not declared with a return type.
Example:
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
This constructor allows us to create Car
objects with initial values for the brand
, model
, and year
fields.
Access modifiers in Java define the visibility and accessibility of fields, methods, and classes. The most common access modifiers are:
public class Car {
private String brand; // Accessible only within the Car class
public String model; // Accessible anywhere
public void setBrand(String brand) {
this.brand = brand;
}
public String getBrand() {
return brand;
}
}
In this example, the brand
field is private
, so it cannot be accessed directly outside the class. However, it can be accessed and modified through the setBrand()
and getBrand()
methods, which are public
.
Encapsulation is the concept of hiding the internal details of an object and exposing only the necessary parts. This is achieved by using private fields and public getter and setter methods.
public class Car {
private String brand;
// Getter method for brand
public String getBrand() {
return brand;
}
// Setter method for brand
public void setBrand(String brand) {
this.brand = brand;
}
}
In this case, the brand
field is hidden from outside access, and it can only be modified using the setBrand()
method and accessed using the getBrand()
method.
Here’s a complete example combining all of the concepts above:
public class Person {
// Fields (properties)
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display information
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
// Setter methods
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
To use the Person
class:
public class Main {
public static void main(String[] args) {
// Create an object of the Person class
Person person = new Person("Alice", 25);
// Call the method
person.introduce();
// Access and modify fields through getter and setter
person.setName("Bob");
person.setAge(30);
// Call the method again with updated values
person.introduce();
}
}
Output:
Hello, my name is Alice and I am 25 years old.
Hello, my name is Bob and I am 30 years old.