Welcome to the world of Object-Oriented Programming (OOP)! OOP is a way to organize your code by creating objects that represent real-world things. This makes your code easier to understand and manage. Let's dive into the basics of OOP with simple examples.
A class is like a blueprint for creating objects. An object is an instance of a class.
public class Dog {
String name;
int age;
void bark() {
System.out.println("Woof! Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // Create an object of the Dog class
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark(); // Call the bark method
}
}In this example, we created a Dog class with attributes name and age, and a method bark. Then, we created an object myDog and used it to call the bark method.
Methods are actions that objects can perform, and attributes are the characteristics of the objects.
public class Car {
String color;
int speed;
void drive() {
System.out.println("The car is driving.");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Create an object of the Car class
myCar.color = "Red";
myCar.speed = 100;
myCar.drive(); // Call the drive method
}
}In this example, we created a Car class with attributes color and speed, and a method drive. Then, we created an object myCar and used it to call the drive method.
Inheritance allows a class to inherit attributes and methods from another class.
class Animal {
void eat() {
System.out.println("This animal is eating.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Meow! Meow!");
}
}
public class Main {
public static void main(String[] args) {
Cat myCat = new Cat(); // Create an object of the Cat class
myCat.eat(); // Call the inherited eat method
myCat.meow(); // Call the meow method
}
}In this example, the Cat class inherits the eat method from the Animal class and also has its own meow method.
Polymorphism allows objects to be treated as instances of their parent class.
class Bird {
void sound() {
System.out.println("This bird makes a sound.");
}
}
class Sparrow extends Bird {
void sound() {
System.out.println("Chirp! Chirp!");
}
}
public class Main {
public static void main(String[] args) {
Bird myBird = new Sparrow(); // Create an object of the Sparrow class
myBird.sound(); // Call the sound method
}
}In this example, the Sparrow class overrides the sound method of the Bird class. When we call the sound method on a Bird reference that points to a Sparrow object, it calls the overridden method in the Sparrow class.
<< Previous | Home | Next >>