Object oriented programming
Introduction
Oops is a programming paradigm(style), based on concept of object & class
Adv of oops: easy to extend/improve, code reusability, readability
Example:
- to understand class object. take shapes as class and box is shape model
Attribute are characteristics of Box ie:length, breadth, height
Methods are abilities/functionalities of Box. eg: calculateVolume(){lbh}
Class
template or blueprint for object (defines variable and methods) ie:noun & verbs
Types of Classes:
- Regular class
- Nested class : OuterClass.InnerClass obj = outerObject.new InnerClass();
- Nested static: OuterClass.NestedStaticClass obj = new OuterClass.NestedStaticClass();
- Anonymous : A obj = new A(){//class body};
Steps to create immutable class:
- Make class as final
- Declare all fields as private and final
- Use parameterized constructor to initialize variables.
- Dont provide setters method
- Return a new instance of objects in the clone() method.
- If using mutable objects, return defensive copies
return new ArrayList<>(hobbies);
Common class Exceptions:
- NoClassDefFoundError: Class present at compiletime but missing at runtime.
- ClassNotFoundException: Occurs during runtime, Class.forName() or loadClass(
Constructor
special type of method, been called while intialize object
Note: it has no return type, cannot be final.
- Default Constructor.
- Parameterized Constructor
super() must call first line of child class constructor
this() will call current class constructor
Object
instant of a class
ClassName obj = new ClassName();
LHS (heap) reference = RHS (stack) instance
Anonymous object
created and used only omce without assigning
new ClassName().functionName();
Methods of Object class:
- toString() - String representation of an Object
- hashCode() - JVM generates a unique number, used for hash based DS.
- equals(Object obj) - Compares the given object to “this” object
- getClass() - Returns the class object of “this” object
Class c = obj.getClass(); c.getClassName();
- finalize() - called just before an object is garbage collected
- clone() - returns a new object
- wait(), notify() notifyAll() - related to Concurrency
4 ways to create object
- New keyword
- clone()
- class.forName(“classname”).newInstance();
- Deserialization while readObject()
Garbage collection
Automatic memory management that destroys objects that are no longer referenced.
- uses Mark and Sweep algorithm
- Garbage first (G1)collector used in java8
- System.gc(); invokes garbage collection.
Ways Garbage Collection is Triggered:
- while nullfying the object rajesh obj1=new rajesh(); obj1=null;
- while assigning reference to other obj1=obj2
- while using anonymous object
Finalize() Method : Called before Garbage Collector
Note: finalize method deprecated in java9 & removed in java18. use AutoCloseable
and try-with-resources
cause OutOfMemoryError
Methods
block of code that perform specific task.
it has methodName, arguments, returnType & returnValue
Varargs : Allows passing a variable number of arguments to a method
void methodname(int ...a){//use as a[];}
Encapsulation:
hiding data
Access Modifiers:
- Public- Any class any package
- Default- Specific package - default if no specifier mentioned
- private - Specified Class
- protected –subsiding class(inheritance)
Non Access Modifiers:
- final - cannot be overrided/modified/extended
- abstract - does not have method body, cannot create object directly
- static - belong to class rather object
- transient - attribute&methods skipped while serialization
- synchronized - can access by one thread at a time
- volatile - value not cached for thread level rather in Main memory level
Note: we cannot use private, protected in class, but we can use in innerclass
Inheritances
one class acquires the properties of another class.
Types of Inheritance
- Single inheritance
- Multilevel inheritance
- Hierarchical inheritance
Super keyword:
- super.variablename;
- super.methodname();
- super(); - explicitly call a specific constructor of the parent class
Note: When child constructor is called, parent constructor is executed first automatically without super().
Polymorphism
ability to define a method(&constructor) in many forms
- Method overriding : same method name, same no. of arguements, same type ie.static/compiletime
- Method overloading : same method name, diff no. of arguements, diff type ie.dynamic/runtime
Method overriding Scenarios:
- Covariant Return Type - allowed
ParentClass getValue(){} -> ChildClass getValue(){}
- Subclass or without Exceptions: allowed
int getValue() throws IOException{} -> int getValue() throws FileNotFoundException{}
int getValue() throws IOException{} -> int getValue(){}
- Access Modifiers - same or narrow access allowed
protected void show()-> public void show()
- Static method: method hiding will happen not overriding
static void show(){} -> static void show(){}
- Synchroniezed method: allowed, no effect
` synchronized void execute() {} -> void execute() {} `
- Varargs Methods: allowed
void log(String... messages) {} -> void log(String... messages) {}
Abstraction
Hiding the implementation
- Abstract(0 to 100% )
- Interface (100%) - variables are public static final by default, methods are public abstract
a) Normal interface
b) Marker interface - empty body eg:cloneable, serializable
c) Functional interface - have only one method declaration
d) defualt access modfier, method which has body
Other Topic
Relationship
- IS-A relationship. also called as inheritance
eg: Circle(child class) IS A Shape(parent class)
- HAS-A reltionship. also called as association.
eg Circle(class) HAS A radius(attribute)
eg: Circle(class) HAS A CalculationUtil(class)
- Aggregation - week bond
eg: Car HAS A MusicPlayer
- Composition - strong bond
eg: Car HAS A Engine