Object-Oriented Programming (OOP) in Java
Step 7:
Hey supper coders ! Now that you know how to use methods, it’s time to dive into Object-Oriented Programming (OOP)—the core of Java that makes it powerful and scalable!
? What is Object-Oriented Programming (OOP)?
OOP is a programming paradigm that organizes code into objects—blueprints for real-world entities like cars, employees, or bank accounts.
??? Key Concepts of OOP in Java
1?? Classes and Objects ???
A class is a blueprint for creating objects.
An object is an instance of a class.
class Car {
String brand = "Tesla";
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Creating an object
System.out.println(myCar.brand); // Output: Tesla
}
}
2?? Encapsulation ??
Encapsulation means hiding data and only allowing access through methods.
class Person {
private String name; // Private variable
public void setName(String newName) { // Setter method
name = newName;
}
public String getName() { // Getter method
return name;
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
System.out.println(p.getName()); // Output: Alice
}
}
3?? Inheritance ???
Inheritance allows a class to reuse features from another class.
领英推荐
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound(); // Output: Animal makes a sound
myDog.bark(); // Output: Dog barks
}
}
4?? Polymorphism ??
Polymorphism allows one interface, multiple implementations.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Cat();
myAnimal.makeSound(); // Output: Cat meows
}
}
5?? Abstraction ??
Abstraction hides implementation details and shows only essential features.
abstract class Vehicle {
abstract void start();
}
class Bike extends Vehicle {
void start() {
System.out.println("Bike starts with a key");
}
}
public class Main {
public static void main(String[] args) {
Bike myBike = new Bike();
myBike.start(); // Output: Bike starts with a key
}
}
? Why is OOP Important?
? Makes code modular and scalable.
? Improves code reusability and organization.
? Helps in building real-world applications efficiently.
?? Coming Up Next:
Exception Handling—how to handle errors gracefully in Java!
Keep going, one step at a time! Stay curious, keep practicing, and let’s unlock Java together! ?
#BinaryBrains
Undergraduate | Web Development
4 周Very Infomative ! ??