Sure! Let’s explain all these Java OOP concepts in simple human language, with easy examples and code.
✅ 1. Class
A class is a blueprint. It tells Java what kind of things (objects) we want to create.
๐ก Example:
public class Dog {
String name;
int age;
public void bark() {
System.out.println(name + " is barking!");
}
}
This is a class called Dog
. It has:
name
,age
(properties)bark()
(behavior)
✅ 2. Object
An object is a real thing created using a class. It has its own values.
๐ก Example:
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // object created
myDog.name = "Tommy";
myDog.age = 3;
myDog.bark(); // output: Tommy is barking!
}
}
✅ 3. Inheritance
Inheritance means one class (child) gets features from another class (parent).
Use extends
keyword.
๐ก Example:
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
class Cat extends Animal {
public void meow() {
System.out.println("Cat says meow.");
}
}
public class Main {
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.eat(); // from Animal
myCat.meow(); // from Cat
}
}
✅ 4. Encapsulation
Encapsulation means hiding the data and only allowing access through methods.
Use private
+ getters/setters
.
๐ก Example:
public class Student {
private String name;
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Arun");
System.out.println(s.getName()); // output: Arun
}
}
✅ 5. Polymorphism
Polymorphism = many forms.
Same method name, different behavior.
✨ Two Types:
- Method Overriding (Run-time)
- Method Overloading (Compile-time)
✅ A. Method Overriding (Sub class changes the method)
class Animal {
public void sound() {
System.out.println("Some animal sound");
}
}
class Dog extends Animal {
public void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // output: Dog barks
}
}
✅ B. Method Overloading (Same method name, different parameters)
class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3)); // 5
System.out.println(c.add(2.5, 4.5)); // 7.0
}
}
๐ฏ Summary Table:
Concept | Meaning |
---|---|
Class | Template or design for objects |
Object | Real instance created from class |
Inheritance | Child class gets properties of parent |
Encapsulation | Hide data using private + getters/setters |
Polymorphism | Same method, different behavior |
Would you like a mini project using all 5 concepts together? ๐จ๐ป
Tidak ada komentar:
Posting Komentar