Java Programs Demonstrating OOP Concepts
Abstraction
abstract class Shape {
abstract void draw(); // abstract method
}
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle");
}
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
}
}
Encapsulation
class Student {
private int age; // private variable
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
Student s = new Student();
[Link](20);
[Link]([Link]());
}
}
Inheritance
class Animal {
void eat() {
[Link]("Animal eats");
}
}
class Cat extends Animal {
public static void main(String[] args) {
Cat c = new Cat();
[Link](); // Inherited method
}
}
Polymorphism
class Vehicle {
void run() {
[Link]("Vehicle is running");
}
}
class Bike extends Vehicle {
void run() {
[Link]("Bike is running");
}
public static void main(String[] args) {
Vehicle v = new Bike(); // Upcasting
[Link](); // Runtime Polymorphism
}
}