In Java, classes and objects are like the building blocks of your program. They help you organize your code and represent real-world things. In this tutorial, we'll break down what classes and objects are in Java.
To create a class, use the keyword class
class CarBlueprint {
String make;
String model;
int year;
}
CarBlueprint myCar = new CarBlueprint();
CarBlueprint car1 = new CarBlueprint(); CarBlueprint car2 = new CarBlueprint();
car1.make = "Toyota"; car1.model = "Camry"; car1.year = 2022;
class CarBlueprint {
void start() {
System.out.println("Car is starting...");
}
}
CarBlueprint myCar = new CarBlueprint();
myCar.start(); // Output: Car is starting...
class Book {
String title;
}
Book myBook = new Book();
myBook.title = "Java Programming";
// Accessing attribute
String bookTitle = myBook.title;
System.out.println("Title: " + bookTitle); // Output: Title: Java Programming
class Book {
String title;
}
Book myBook = new Book();
myBook.title = "Java Programming";
// Modifying attribute
myBook.title = "Java Mastery";
System.out.println("New Title: " + myBook.title); // Output: New Title: Java Mastery
class Calculator {
int add(int a, int b) {
return a + b;
}
}
Calculator myCalculator = new Calculator();
// Invoking method
int sum = myCalculator.add(5, 7);
System.out.println("Sum: " + sum); // Output: Sum: 12
class Bird {
void sing() {
System.out.println("Bird is singing...");
}
}
class Parrot extends Bird {
void sing() {
System.out.println("Parrot is singing loudly!");
}
}
Bird myBird = new Parrot();
// Invoking method
myBird.sing(); // Output: Parrot is singing loudly!