Hello once again, Java enthusiasts!
In this session, we delve into the core of Java programming – Object-Oriented Programming (OOP). Java is fundamentally an object-oriented language, meaning it uses objects and classes as the primary elements for organizing code. Understanding objects and classes is crucial for mastering Java.
1. Classes in Java
A class in Java is a blueprint for creating objects. It defines a datatype by bundling data and methods that operate on the data into one single unit.Example of a Simple Java Class:
public class Car {
// Attributes (or fields)
String brand;
int year;
// Constructor
Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
// Method
public void displayInfo() {
System.out.println("Car Brand: " + brand + ", Year: " + year);
}
}
In this example, Car is a class with attributes brand and year, a constructor to initialize the attributes, and a method displayInfo to display the car’s information.
2. Objects in Java
An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created.Creating and Using an Object:
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Toyota", 2020);
// Calling a method on the myCar object
myCar.displayInfo();
}
}
In this example, myCar is an object of the Car class. The new keyword is used to create the object.
Exercise:
Create a Simple Java ClassNow, let’s practice by creating a simple Java class. Here’s a small exercise:- Create a class named Book.
- Add attributes like title, author, and year.
- Write a constructor to initialize these attributes.
- Add a method to display information about the book.
Conclusion
Excellent work! You’ve now stepped into the world of Object-Oriented Programming in Java. Classes and objects are the backbone of Java and are essential for building robust and scalable applications.Practice creating different classes and objects to deepen your understanding of OOP in Java. This knowledge forms the foundation for more advanced programming concepts you’ll encounter later.Enjoy your Java programming journey, and stay curious!