java_oop_concepts_final
java_oop_concepts_final
class Student {
String name;
int age;
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
Output:
Name: John, Age: 20
2. Constructor
class Car {
String model;
Car(String m) {
model = m;
}
void display() {
System.out.println("Car Model: " + model);
}
Output:
Car Model: Toyota
3. Destructor (Finalizer)
class FinalizerDemo {
protected void finalize() {
System.out.println("Object is garbage collected");
}
Output:
Object is garbage collected (May vary depending on GC execution)
4. Single Inheritance
class Animal {
void sound() {
System.out.println("Animals make sound");
}
}
Output:
Animals make sound
Dog barks
5. Multilevel Inheritance
class Animal {
void eat() {
System.out.println("Animals eat food");
}
}
Output:
Animals eat food
Mammals walk
Humans speak
6. Hierarchical Inheritance
class Animal {
void eat() {
System.out.println("Animals eat food");
}
}
Output:
Animals eat food
Dog barks
Animals eat food
Cat meows
7. Method Overloading
class MathOperations {
int add(int a, int b) {
return a + b;
}
Output:
Sum (int): 15
Sum (double): 16.0
8. Method Overriding
class Parent {
void show() {
System.out.println("Parent's show method");
}
}
Output:
Child's show method
9. Abstract Class
Output:
Drawing Circle
10. Interface
interface Animal {
void makeSound();
}
Output:
Dog barks
11. Static Keyword
class StaticExample {
static int count = 0;
StaticExample() {
count++;
System.out.println("Object count: " + count);
}
Output:
Object count: 1
Object count: 2
Object count: 3
12. Encapsulation
class Person {
private String name;
Output:
Name: John
13. Polymorphism (Runtime)
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
Output:
Dog barks
14. File Handling
import java.io.FileWriter;
import java.io.IOException;
class FileDemo {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, File Handling in Java!");
writer.close();
System.out.println("File written successfully");
} catch (IOException e) {
System.out.println("An error occurred");
}
}
}
Output:
File written successfully (A file named output.txt will be created)
15. Exception Handling
class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}
Output:
Cannot divide by zero