Welcome to the Java Object-Oriented Programming (OOP) Introduction lesson! š In this tutorial, we'll explore the fundamentals of Java OOP, making it easy for both beginners and intermediates to understand and apply these concepts.
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, objects, and methods. It encourages modularity, reusability, and a clean separation of concerns.
Let's start by creating a simple class to represent a Person.
public class Person {
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
}š” Pro Tip: A class in Java starts with an uppercase letter, and methods and variables are camelCase.
Now, let's create an instance of our Person class and use it to display details.
public class Main {
public static void main(String[] args) {
Person johnDoe = new Person("John Doe", 30);
johnDoe.displayDetails();
}
}When you run this code, you'll see the following output:
Name: John Doe, Age: 30
Inheritance allows one class (the subclass) to inherit properties and methods from another class (the superclass). Here's an example with a Student class inheriting from the Person class.
public class Student extends Person {
String studentId;
// Constructor
public Student(String name, int age, String studentId) {
super(name, age); // Call the Person constructor
this.studentId = studentId;
}
}Polymorphism allows objects to take multiple forms. In Java, it can be achieved through method overriding and method overloading.
public class Vehicle {
String name;
public void move() {
System.out.println("Moving...");
}
}
public class Car extends Vehicle {
@Override
public void move() {
System.out.println("Driving...");
}
}
public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
car.move(); // Output: Driving...
}
}Encapsulation hides the internal details of an object, promoting data privacy and integrity.
public class Account {
private int balance;
public void deposit(int amount) {
balance += amount;
}
public int getBalance() {
return balance;
}
}š” Pro Tip: Use the private keyword to mark variables that should be encapsulated.
What is polymorphism in Java?
Congratulations on completing the Java OOP Introduction lesson! You've learned the basics of classes, objects, inheritance, polymorphism, and encapsulation. With this knowledge, you're well on your way to mastering Java Object-Oriented Programming.
Keep coding, and happy learning! šš