-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOOPPrinciples.java
More file actions
65 lines (57 loc) · 1.8 KB
/
Copy pathOOPPrinciples.java
File metadata and controls
65 lines (57 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
*
* Q. What are the core principles of Object-Oriented Programming (OOP)? Explain each with an example in Java.
* Ans. Explanation of core principles of Object-Oriented Programming (OOP) with Java examples
* Approach
* Define the four core OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction
* Provide a brief explanation for each principle
* Include a simple Java code example demonstrating each principle
*
*
* **/
public class OOPPrinciples {
// Encapsulation example
static class Encapsulation {
private int data;
public void setData(int data) { this.data = data; }
public int getData() { return data; }
}
// Inheritance example
static class Animal {
public void sound() { System.out.println("Animal sound"); }
}
static class Dog extends Animal {
@Override
public void sound() { System.out.println("Dog barks"); }
}
// Polymorphism example
static class Shape {
public void draw() { System.out.println("Drawing shape"); }
}
static class Circle extends Shape {
@Override
public void draw() { System.out.println("Drawing circle"); }
}
// Abstraction example
abstract static class Vehicle {
abstract void move();
}
static class Car extends Vehicle {
void move() { System.out.println("Car is moving"); }
}
public static void main(String[] args) {
Encapsulation e = new Encapsulation();
e.setData(10);
System.out.println("Encapsulation data: " + e.getData());
Animal a = new Animal();
a.sound();
Dog d = new Dog();
d.sound();
Shape s = new Shape();
s.draw();
Shape c = new Circle();
c.draw();
Vehicle v = new Car();
v.move();
}
}