-
Notifications
You must be signed in to change notification settings - Fork 0
YourNote 101: OOP
Zhamri Che Ani edited this page Apr 30, 2026
·
1 revision
A class is a blueprint for creating objects.
class Car {
String brand;
int speed;
void drive() {
System.out.println("The car is driving.");
}
}An object is an instance of a class.
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Creating object
myCar.brand = "Toyota";
myCar.speed = 120;
myCar.drive();
}
}- Hiding data using private variables
- Accessing them using getters and setters
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}One class inherits properties of another using extends
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}Same method name, different behavior
class MathOperation {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}- Hiding implementation details
- Achieved using abstract classes or interfaces
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing circle");
}
}interface Animal {
void sound();
}
class Cow implements Animal {
public void sound() {
System.out.println("Moo");
}
}