- Objects share two characteristics: They all have
state andbehavior . - Instance is an instantiation of a class.
- Class is a blueprint that defines object's state and behavior.
- A class encapsulates the static attributes (data) and dynamic behaviors (operations that operate on the data) in a box.
- Class >> Object >> Instance (object is instance of class)
- Declare an instance identifier (instance name) of a particular class.
- Construct the instance (i.e., allocate storage for the instance and initialize the instance) using the "new" operator.
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 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) calledoverload 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 can be used to refer current class instance variable.
- this can be used to invoke current class method (implicitly)
- this() can be used to invoke current class constructor.
- this can be passed as an argument in the method call.
- this can be passed as argument in the constructor call.
- this can be used to return the current class instance from the method.
Definition: one object acquires all the properties and behaviors of parent object.
It is a
Why use Inheritance?
create new classes that are built upon existing classes.
reuse methods and fields of parent class, and add more functions.
Types of Inheritance:
1. single
2. multilevel
3. hierarchical
Important facts about inheritance
Default superclass : Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object class.Superclass can only be one : A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritance with classes. Although with interfaces, multiple inheritance is supported by java.Inheriting Constructors : A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.Private member inheritance : A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass.
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.
- Provide easy maintenance.
- You can control the way that accessing the variables, so that you can prevent the data being randomly accessed by other classes.
- Increase reusability
- Encapsulation is data hiding while Abstraction is detail hiding.
- While encapsulation groups data and methods together, data abstraction deals with exposing the interface to the user and hiding the details of implementation.
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.
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.
2.
Overriding the static method
If you try to override a static method, it is known as
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 variable: final variable cannot be changed.
final method: cannot override it. But final method is inherited.
final class: cannot extend it.
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.
Compile time/static polymorphism
Polymorphism that is resolved during
Run time/dynamic polymorphism
Method overriding: overridden method is resolved at
Composition over inheritance
classes should achieve polymorphic behavior and code reuse by their composition rather than inheritance from a base or parent class.
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
If there is any
why
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.
- Abstraction: a process of hiding the implementation details and showing only functionality to the user.
- Two ways to achieve abstraction:
abstract class , andinterface . - An abstract class can not be instantiated, which means you are not allowed to create an object of it.
- Abstract class doesn't provide 100% abstraction because it allows concrete methods. However, Interface provides 100% abstraction.
- A class derived from the abstract class must implement
ALL those methods that are declared as abstract in the parent class. - If a child does not implement all the abstract methods of abstract parent class, then the child class must need to be declared abstract as well.
- How to use abstract class: extend it and build. Can't create object since there are no implementation.
Why use interface?
1. To achieve full abstraction.
2. multiple inheritance.
Rules:
- Interface can only have
abstract methods. Don't have to put "interface" on the header. - Can extends multiple interfaces.
- If interface1 extends interface2, class implements interface1, then class must implements all methods in both interface1 and interface2.
- Cannot create object of interfaces.
- Variables declared in interface are
public, static, final by default.
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: 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.
- A singleton class is a class that can have only one object (an instance of the class) at a time.
- Purpose of using
Singleton :- control
object creation , limiting the number of objects toonly one . - Singletons often control
access to resources , such as database connections or sockets.- For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.
- control
- Implementation:
- Make constructor as private.
- Write a static method that has return type object of this singleton class.
- Lazy Initialization - used for single thread
- Sample Singleton class:
public class Singleton { private static Singleton singleton_instance = null; /* A private Constructor prevents any other * class from instantiating. */ private Singleton() { } /* Static 'instance' method */ public static Singleton getInstance( ) { if(singleton_instance == null) { singleton_instance = new Singleton(); } return singleton_instance; } /* Other methods protected by singleton-ness */ protected static void demoMethod( ) { System.out.println("demoMethod for singleton"); } }
- Creating a Singleton class object:
public class SingletonDemo { public static void main(String[] args) { Singleton tmp = Singleton.getInstance( ); tmp.demoMethod( ); } }
- Sample Singleton class:
- Double Checked Locking
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){ if(instance == null){ synchronized (ThreadSafeSingleton.class) { if(instance == null){ instance = new ThreadSafeSingleton(); } } } return instance; }