Java Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which are instances of classes. Java is an object-oriented language that supports the following features:
- Encapsulation - Bundling data and methods that operate on the data within one unit (class).
- Inheritance - Mechanism where one class inherits the properties and behavior of another class.
- Polymorphism - Ability to take many forms, i.e., methods or classes behaving differently based on the context.
- Abstraction - Hiding complex implementation details and showing only essential features.
Creating a Simple Class and Object
public class Person {
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
public class OOPExample {
public static void main(String[] args) {
Person person1 = new Person("John", 25);
person1.introduce();
}
}
This example demonstrates how to create a simple class Person with a constructor and a method introduce. An object of the class is created in the main method and its introduce method is called.