Topics Covered in this Page
  1. What is Object, Instance, Class?
  2. Constructors
  3. static keyword
  4. this keyword
  5. final keyword
  6. Inheritance
  7. Method Overloading/Overriding
  8. Polymorphism
  9. Static Binding and Dynamic Binding
  10. Abstract Class
  11. Interface
  12. Singleton
What is Object, Instance, Class? Creating Instances of a Class Constructors

A constructor is used to construct and initialize all the member variables. The name of the constructor method is the same as the class name.
Constructor has no return type. It implicitly returns void.
Constructor can only be invoked via the "new" operator.
Constructors are not inherited.
Java compiler creates a default constructor(no-arg constructor) if your class doesn't have any. Default constructor is used to provide the default values to the object like 0, null etc. depending on the type.

Constructor overloading: Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
Example:

                        class Student5{  
                            int id;  
                            String name;  
                            int age;  
                            Student5(int i,String n){  
                                id = i;  
                                name = n;  
                            }  
                            Student5(int i,String n,int a){  
                                id = i;  
                                name = n;  
                                age=a;  
                            }  
                            void display(){System.out.println(id+" "+name+" "+age);}  
                            
                            public static void main(String args[]){  
                                Student5 s1 = new Student5(111,"Karan");  
                                Student5 s2 = new Student5(222,"Aryan",25);
                            }  
                        }
                    


static keyword

static variable

It makes the program memory efficient. static property is shared to all objects.


static method

A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.

Restrictions:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.

When to use static method?
If you are writing utility classes and they are not supposed to be changed.
If the method is not using any instance variable.
If any operation is not dependent on instance creation.

overload static method?
Yes.

                        public class Test {
                            public static void foo() {
                                System.out.println("Test.foo() called ");
                            }
                            public static void foo(int a) { 
                                System.out.println("Test.foo(int) called ");
                            }
                            public static void main(String args[])
                            { 
                                Test.foo();
                                Test.foo(10);
                            }
                        }
                        /********************/
                        Output:
                        Test.foo() called 
                        Test.foo(int) called 
                    
overload methods that differ only by static keyword?
No.
                        public class Test {
                            public static void foo() {
                                System.out.println("Test.foo() called ");
                            }
                            public void foo() { // Compiler Error: cannot redefine foo()
                                System.out.println("Test.foo(int) called ");
                            }
                            public static void main(String args[]) { 
                                Test.foo();
                            }
                        }
                        /********************/
                        Output: Compiler Error, cannot redefine foo()
                    


this keyword

Inheritance

Definition: one object acquires all the properties and behaviors of parent object. It is a IS-A relationship, also known as parent-child relationship. The subclass can add its own fields and methods in addition to the superclass fields and methods.

Why use Inheritance?
1. Code reusability
create new classes that are built upon existing classes.
reuse methods and fields of parent class, and add more functions.
2. For Method Overriding

Types of Inheritance:
1. single
2. multilevel
3. hierarchical

Important facts about inheritance


Encapsulation

Definition: Wrapping data and methods together.
To achieve encapsulation, you can create private variables to hide the data, and provide getter method for other classes to get the private variables.
Advantages:

Encapsulation vs Abstraction


Method Overloading

Definition: same name with different parameters.
why use? Increases the readability of the program.
Overload main method? Yes. But JVM calls main() method which receives string array as arguments only.


Method Overriding

Definition:If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
why use?
1. used for provide specific implementation of a method that is already provided by its super class.
2. used for runtime polymorphism.

Rules for Java Method Overriding
1. method must have same name as in the parent class.
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Facts:
1. Override static method? No
2. Override main method? No, main() is static

Overriding the static method
If you try to override a static method, it is known as hiding or shadowing.

                        public class PolymorphismTest {
                            public static void main(String[] args) {
                                Base b = new DerivedOne();
                                b.f(); // prints "Base"
                            
                                b = new Base();
                                b.f();  //prints "Base"
                            }
                        }

                        /*
                            Why prints "Base" in both cases? Because, it only looks at what type variable "b" is? 
                            In both cases of type Base. It does not care what type of object is stored. 
                            Same for variables, and is known as "Shadowing"
                        */
                    


final keyword

final variable: final variable cannot be changed.
final method: cannot override it. But final method is inherited.
final class: cannot extend it.


Polymorphism

Definition:perform a single action by different ways. There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism.

Example:Animal class has sound() method. Cat and Horse extends Animal. Cat implements "Meow", and Horse implements "Neigh".
This is one method used in multiple ways. One interface with multiple implementations.

Compile time/static polymorphism
Polymorphism that is resolved during compiler time is known as static polymorphism.
Method overloading is compile time polymorphism because which method to be called is determined at the run time based on the parameters.

Run time/dynamic polymorphism
Method overriding: overridden method is resolved at run time.
Composition over inheritance
Composition: Has-A relationship. Containing instances of other classes that implement the desired functionality.
classes should achieve polymorphic behavior and code reuse by their composition rather than inheritance from a base or parent class.


Static Binding and Dynamic Binding

What is binding?
Connecting a method call to the method body is known as binding.

Two types:
- static binding (early binding)
- dynamic binding (late binding)

static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.

why private, final or static method is static binding?
Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn't have any difficulty to determine object of class (local class for sure).

dynamic binding
Dynamic binding is a binding which happens during run time.
Method overriding is dynamic binding since the type of the object is determined at the run time.


Abstract Class

Rules:

Interface

Why use interface?
1. To achieve full abstraction.
2. multiple inheritance.

Rules:


When to use Abstract Class vs Interface
Abstract classes should primarily be used for objects that are closely related (some classes might need to share lines of code, so you can put these code to abstract class). Need to provide default implementation.
Interfaces are better at providing common functionality for unrelated classes. If need multiple inheritance.

Association > Aggregation > Composition
Association: relation between classes objects. Can be one-to-one, one-to-many, many-to-one, many-to-many. Composition and Aggregation are two forms of Association.
Aggregation: Has-A relationship. Unidirectional. Entities are independent.
Composition: restricted form of Aggregation. part-of relationship. Entities are dependent.
Singleton