OOP Java Code Examples
OOP Java Code Examples
class Car {
String model;
int year;
void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
2. Encapsulation
Example: Protecting balance in a BankAccount class.
class BankAccount {
private double balance; // private = encapsulated
3. Inheritance
Example: Dog inherits from Animal.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
4. Polymorphism - Overriding
Method Overriding (Runtime Polymorphism)
class Animal {
void sound() {
System.out.println("Generic animal sound");
}
}
4. Polymorphism - Overloading
Method Overloading (Compile-time Polymorphism)
class Calculator {
int add(int a, int b) {
return a + b;
}
5. Abstraction
Example: Abstract Shape class.
6. Interface
Example: Using interface for multiple behaviors.
interface Printable {
void print();
}