Key Features of OOP
- Encapsulation: Binding Data & methods that operate on data together in a single unit is called Encapsulation. This is achieved through the use of Classes & Objects.
- Abstraction: Hiding unnecessary implementation details from the outer world and showing only important usable details of an object is called Abstraction. This is achieved through the use of access modifiers – public, private & protected.
- Inheritance: A Class can inherit properties & methods from another class using Inheritance. The subclass can inherit properties and methods from a class (base class) and then either add more properties/methods or redefine existing methods of the base class.
- Polymorphism: The term “Polymorphism” means many forms. In OOP, it refers to superclass & subclass having the same method names but different implementations or parameters.
Unique OOP Features in Java
These are the OOP features provided by Java, which are provided by only a few other or no other programming languages.
- Interfaces
- Abstract Classes
- Exception Handling
- Garbage Collector
New OOP Features in Java 8:
- Interface with default methods & static methods
- Functional Interfaces
- Method References
- Optional Class
Java Syntax for Object-Oriented Programming
Class Declaration
class ClassName {
// Fields (variables)
// Methods (functions)
// Constructors
}
Access specifiers (public, private, protected) should be mentioned before each member declaration.
Object Creation / Instantiating a Class
ClassName objectName = new ClassName(parameters);
Constructor
ClassName(); // Default constructor
ClassName(type param); // Parameterized constructor
Accessing Objects
ObjectName.property;
ObjectName.method();
Inheritance
class Subclass extends Superclass {
// New fields and methods
// Overridden methods
}
Member Function Declaration
access_modifier return_type method_name(parameters);
Static Members
static dataType variableName;
static access_modifier returnType method_name(parameters);
Method Overloading
access_modifier returnType methodName(parameters);
access_modifier returnType methodName(different_parameters);
Abstract Method
abstract returnType methodName(parameters);
Abstract Class
abstract class AbstractClassName {
abstract returnType methodName(parameters);
// Concrete methods
}
Interface
interface InterfaceName {
returnType methodName(parameters);
}
Implementing an Interface
class ClassName implements InterfaceName1, InterfaceName2 {
@Override
returnType methodName(parameters) {
// Method body
}
}
Destructor
The finalize() method name is used for implementing destructor in Java, This method is called when an object is cleaned by Garbage Collector
protected void finalize()