Quick Refresh : Core Java : Constructor, instanceOf, Downcasting, Access Modifiers, abstract, final, static, this, instance initializer block


Quick Refresh : Core Java : Constructor, instanceOf, Downcasting, Access Modifiers, abstract, final, static, this, instance initializer block



A field is a class member. A static field is sometimes called a class variable. A non-static field is sometimes called an instance variable. A variable declaration that is immediately contained by a block such as a method body is called a local variable. The access modifiers, private, protected and public, can be applied to a field. 

Constructor: Constructor is a special type of method that is used to initialize the state of an object. Constructor is invoked at the time of object creation. It constructs the values i.e. data for the object that is why it is known as constructor.
Types of constructors
  • Default Constructor - Default constructor provides the default values to the object.
  • Parameterized Constructor - A constructor that have parameter is known as parameterized constructor. Parameterized constructor is used to provide different values to the distinct objects.
Rules for creating constructor
  • Constructor name must be same as its class name
  • Constructors do not return a value and constructor declarations do not include a return type, so the keyword void is not applicable to a constructor declaration. 
If no constructor is declared explicitly, then the compiler will implicitly create a default constructor that accepts no parameters, has no throws clause, and invokes its superclass constructor. 

The explicit declaration of any constructor will prevent the creation of a default constructor. If all constructors are declared private, then code outside of the class will not have access to the constructors and will not have the ability to create an instance of the class.  

Constructor Overloading: 
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Q)Does constructor return any value?
A) yes,that is current class instance (You cannot use return type yet it returns a value).

Copying the values of one object to another
  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class
The instanceof operator

The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof operator is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that have null value, it returns false. 
class Animal{}

class Dog extends Animal{//Dog inherits Animal

 public static void main(String args[]){
 Dog d=new Dog();
 System.out.println(d instanceof Animal);//true
 Dog d1= null;
  System.out.println(d1 instanceof Animal);//false
 }
}

Downcasting:
  • When Subclass type refers to the object of Parent class, it is known as downcasting.
         Dog d=new Animal();//Compilation error
  • If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime.
        Dog d=(Dog)new Animal(); //Compiles successfully but ClassCastException is thown at runtime
  • if we use instanceof operator, downcasting is possible.
class Animal { }
class Dog extends Animal {
  static void method(Animal a) {
    if(a instanceof Dog){
       Dog d=(Dog)a;//downcasting
       System.out.println("ok downcasting performed");
    }
  }
  public static void main (String [] args) {
    Animal a=new Dog();
    Dog.method(a);
  }
  
}
Output:ok downcasting performed

Modifiers: There are two types of modifiers access modifier and non-access modifier. 

Access Modifiers: The access modifiers specifies accessibility (scope) of a datamember, method, constructor or class. There are 4 types of access modifiers:

private - The private access modifier is accessible only within class. A class cannot be private or protected except nested class.
     Note: If you make any class constructor private, you cannot create the instance of that class from outside the class.
default - If you don't use any modifier, it is treated as default modifier bydefault. The default modifier is accessible only within package.
protected - The protected access modifier is accessible within package and outside the package by only through inheritance. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
public - The public access modifier is accessible everywhere. It has the widest scope among all other modiers.

Applying access modifier with method overriding: If you are overriding any method, overriden method (i.e. declared in subclass) must not be more restrictive.

Non-Access Modifiers: There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. 


Abstraction: Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details. Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstaction- There are two ways to achieve abstraction in java
  1. Abstract class (0 to 100%)- A class that is declared as abstract is known as abstract class.It needs to be extended and its method implemented. It cannot be instantiated.
  2. Interface (100%) - An interface is a blueprint of a class. It has static constants and abstract methods. There are mainly three reasons to use interface-
    • It is used to achieve fully abstraction.
    • By interface, we can support the functionality of multiple inheritance. - A class cannot extend two classes but it can implement two interfaces.
    • It can be used to achieve loose coupling.
         Note: 
    • The java compiler converts methods of interface as public and abstract, data members as public,final and static bydefault.
    • A class implements interface but One interface extends another interface .
    • An interface can have another interface i.e. known as nested interface.
    • Marker or Tagged interface - An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
            abstract Keyword: The abstract modifier may be applied to methods and class but not to fields.   
            • abstract class- A class that is declared as abstract is known as abstract class.It needs to be extended and its method implemented. It cannot be instantiated. An abstract class may include zero, one or more abstract methods.
            Syntax to declare the abstract class-    abstract class <class_name>{}
            • abstract method- A method that is declared as abstract and does not have implementation is known as abstract method. An abstract method declaration provides no method body. If one abstract method is appears within a class declaration, then the entire class must be declared abstract and the class can not be instantiated. 
            Syntax to define the abstract method-   abstract return_type <method_name>();

            Note: An abstract class can have data member,abstract method,method body,constructor and even main() method.

            Rule: If you are extending any abstact class that have abstract method, you must either provide the implementation of the method or make this class abstract.

            final Keyword:  
            The final keyword in java is used to restrict the user. The final keyword can be used in many context. final can be:
            1. final variable: If you make any variable as final, you cannot change the value of final variable(It will be constant).
            2. final method: If you make any method as final, you cannot override it.
            3. final class: If you make any class as final, you cannot extend it.
            4. blank final variable: The final keyword can be applied with the variables, that have no value it is called blank final variable. It can be initialized in the constructor only. 
            5. static blank final variable: The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
            6. final parameter: If you declare any parameter as final, you cannot change the value of it.

            Que) Is final method inherited?
            Ans)Yes, final method is inherited but you cannot override it.

            Que)Can we declare a constructor as final?
            Ans)No, because constructor is never inherited.

            static Keyword: The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods and blocks. The static keyword belongs to the class than instance of the class. The static can be:
            • variable (also known as class variable) - The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. The static variable gets memory only once in class area at the time of class loading. Advantage of static variable is that it makes your program memory efficient.
            • method (also known as class 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 for static method

              • 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.
              Q)why main method is static?
              A) because object is not required to call static method if it were non-static method, jvm creats object first then call main() method that will lead  the problem of extra memory allocation.
                • block - Is used to initialize the static data member. It is excuted before main method at the time of classloading.
                Que)Can we execute a program without main() method?
                Ans)Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

                class A{
                  static{
                  System.out.println("static block is invoked");
                  System.exit(0);
                  }

                }


                Note:  The static modifier can be applied to a class that is a member of an enclosing class, but can not be applied to a local class or a class that is not nested inside another class.

                this keyword: this is a reference variable that refers to the current object.
                Usage of this keyword

                • to refer the current class instance variable - If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity. If local variables(formal arguments) and instance variables are different, there is no need to use this keyword
                • to invoke the current class constructor - This approach is better if you have many constructors in the class and you want to reuse that constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining.
                Rule: Call to this() must be the first statement.

                • to invoke the current class method - You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. 
                • to pass as an argument in the method call - In event handling (or) in a situation where we have to provide reference of a class to another one.
                • to pass as an argument in the constructor call -It is useful if we have to use one object in multiple classes. 
                • to return the current class instance - In such case, return type of the method must be the class type (non-primitive).

                super keyword: super is a reference variable that is used to refer immediate parent class object.
                Uses of super Keyword:
                • super is used to refer immediate parent class instance variable.
                • super() is used to invoke immediate parent class constructor.
                • super is used to invoke immediate parent class method.
                Instance initializer block: Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. The initialization of the instance variable can be directly but there can be performed extra operations while initilizing the instance variable in the instance initializer block.

                Rules for instance initializer block :
                • The instance initializer block is created when instance of the class is created.
                • The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
                • The instance initializer block comes in the order in which they appear.
                Why use instance initializer block?
                Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to fill a complex array or error handling etc.

                What is invoked firstly instance initializer block or constructor?
                Instance intializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the costructor after the first statement super(). So firstly, constructor is invoked.
                Note: The java compiler copies the code of instance initializer block in every constructor.

                strictfp keyword: The strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language have provided the strictfp keyword, so that you get same result on every platform. So, now you have better control over the floating-point arithmetic. The strictfp keyword can be applied on methods, classes and interfaces.

                Note: The field modifiers, transient and volatile, are not applicable to method declarations.  
                Note: If the superclass method is declared static, then any subclass method sharing the same signature must also be declared static. Similarly, if the superclass method is declared non-static, then any subclass method sharing the same signature must also be declared non-static.


                Order of execution of Initialization blocks and constructor in Java
                • Static initialization blocks will run whenever the class is loaded first time in JVM
                • Initialization blocks run in the same order in which they appear in the program.
                • Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces.
                // execution of constructors, static and initialization blocks
                class ABC{

                ABC(int x)
                {
                System.out.println("ONE argument constructor");
                }

                ABC()
                {
                System.out.println("No argument constructor");
                }

                static
                {
                System.out.println("1st static init");
                }

                {
                System.out.println("1st instance init");
                }

                {
                System.out.println("2nd instance init");
                }

                static
                {
                System.out.println("2nd static init");
                }

                public static void main(String[] args)
                {
                new ABC();
                new ABC(8);
                }
                }

                Output:

                1st static init
                2nd static init
                1st instance init
                2nd instance init
                No argument constructor
                1st instance init
                2nd instance init
                ONE argument constructor

                Comments

                Popular posts from this blog

                Ashtavinayak Temples | 8 Ganpati Temples of Maharashtra | Details Travel Reviews

                Ramoji Film City, Hyderabad, India

                Pune to Ganpatipule Trip