Java OOPs Basics to Intermediate (Compared with C++)
1. Class:
- Java: Blueprint to create objects; defined using 'class' keyword.
- C++: Same concept, also supports 'struct' for data grouping.
Example:
Java: class Car { String color; void drive(){} }
C++: class Car { string color; void drive(){}; };
2. Object:
- Java: Instance of a class, created with 'new' keyword.
- C++: Similar, but can create on stack without 'new'.
Example:
Java: Car obj = new Car();
C++: Car obj; or Car* obj = new Car();
3. Instance:
- Refers to an actual object of a class.
4. Abstraction:
- Java: Achieved via abstract classes and interfaces.
- C++: Achieved via abstract classes (pure virtual functions).
5. Encapsulation:
- Wrapping data (fields) and methods together.
- Java & C++: Done via access modifiers (private, public, protected).
6. Inheritance:
- Java: Single, multilevel, hierarchical. No multiple inheritance (use interfaces).
- C++: Supports multiple inheritance.
Example:
Java: class A{} class B extends A{}
C++: class B : public A {}
7. Polymorphism:
- Compile-time (overloading) and Runtime (overriding).
- Java: Method overloading & overriding.
- C++: Function overloading, operator overloading & virtual functions.
8. Overloading:
- Same method name, different parameters.
- Java: Only method overloading.
- C++: Method and operator overloading.
9. Overriding:
- Subclass provides specific implementation for a method in parent class.
10. Constructor:
- Java: Special method with same name as class.
- C++: Same concept, but supports initializer lists.
11. this keyword:
- Java: Refers to current object.
- C++: Same, using pointer 'this'.
12. super keyword:
- Java: Refers to parent class.
- C++: Use scope resolution (::) for parent members.
13. Access Modifiers:
- Both have public, private, protected.
14. Interface:
- Java: 100% abstraction; class implementing must define methods.
- C++: Use pure virtual functions in abstract class.
15. Final keyword (Java):
- Used to make variables constant, prevent method overriding, or inheritance.
- C++ equivalent: const, final (C++11).
Conclusion:
Both Java and C++ share core OOPs principles but differ in syntax, memory management, and inheritance