OOPS – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 09:05:37 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 OOPS – Java2Blog https://java2blog.com 32 32 Difference between early binding and late binding in java https://java2blog.com/difference-between-early-binding-and-late-binding-java/?utm_source=rss&utm_medium=rss&utm_campaign=difference-between-early-binding-and-late-binding-java https://java2blog.com/difference-between-early-binding-and-late-binding-java/#comments Wed, 30 Jan 2019 17:47:19 +0000 https://www.java2blog.com/?p=4693 Binding in Java refers to the process of associating a method or function body with a method or function call by the Java Compiler. In simpler words, when a function is called by the Java compiler the task of correctly locating the method for the respective function is binding. Depending on when the compiler is able to associate a method body with its method call, binding in java is classified into two main headers:

  • Early Binding, also known as Static Binding
  • Late Binding, also known as Dynamic Binding

Let us go through these two types in detail.

Early Binding or Static Binding

As mentioned earlier, binding refers to the process of associating or “binding” a method body with its call. Early or Static Binding refers to the association of these two entities at compile time by the Java Compiler. Static binding is used to associate any private, final or static method bodies with their method call statements prior any execution taking place. The best instance of early binding is method overloading.

Why are static final and private methods associated by Early Binding?

This is due to the fact that static, final or private methods cannot be overridden by any subclass and hence they are always referred to by a constant reference, i.e. the class in which they are defined. Due to this property of static, final or private methods, the java compiler can easily determine pre-execution that those methods can only be referenced by an object of the class they are defined in.

The following example shall demonstrate Static Binding.

Code Example:

class Car {

    public static void startEngine(){
        System.out.println("Car Engine Started");
    }
}

public class Porsche extends Car {

    public static void startEngine(){
        System.out.println("Porche's Engine Started");
    }

    public static void main(String args[]){

        Car car1 = new Porsche();
        Car car2 = new Car();
        car1.startEngine();
        car2.startEngine();
    }
}

Output:

Car Engine Started
Car Engine Started

Analysis:

If we analyze the output of the above code, we notice that despite overriding the “startEngine” method in derived class Porsche and initializing the object “car1” with the reference of the class Porsche, the method “startEngine()” method was not overridden and printed the text of the superclass Car.

This was due to the fact that the static method “startEngine()” of the class Car cannot be overridden and was bound by the java compiler during compilation.

Now let us have a look at the other form of Binding:

Late Binding or Dynamic Binding

If the compiler is unable to determine which method call a particular method is bound during compilation, then it resorts to late binding or dynamic binding. The best instance of dynamic binding is Method Overriding. A subclass overrides the method of the super class and during execution, methods get associated with their respective references.

It may be noted here that that for Dynamic Binding to occur, it is imperative that the method to be overridden is not declared as static, final or private. Declaring the method with any of the above modifiers will prevent it from being overridden and java will resort to static binding as it can easily determine the parent reference.

Let us observe dynamic binding by using the previous example. Only this time, the methods will no longer be declared as “static”

Code Example:

class Car {

    public void startEngine(){
        System.out.println("Car Engine Started");
    }
}

public class Porsche extends Car {

    public void startEngine(){
        System.out.println("Porche's Engine Started");
    }

    public static void main(String args[]){

        Car car1 = new Porsche();
        Car car2 = new Car();
        car1.startEngine();
        car2.startEngine();
    }
}

Output:

Porche’s Engine Started
Car Engine Started

Analysis:

The difference in output is noticeable, as the first method call has successfully bound the reference of the class Porsche and called the overridden method “startEngine()”. As we have no longer used the static keyword as a modifier to the method, the java compiler could not find a reference to bind the method to during compilation and hence resorted to Dynamic binding and the type or reference of the method was determined at runtime.

Differences between Static and Dynamic Binding

Static BindingDynamic Binding
Static or Early Binding takes place at compile time.Dynamic or Late Binding takes place during runtime
Methods declared as private, static or final show static binding as they cannot be overridden and can be associated, during compilationMethods which are public, protected or default show dynamic binding as they can be overridden and their reference is associated only at runtime
Actual object reference is not used in early bindingActual object reference is used
Method overloading is the best example of Static or Early BindingMethod Overriding is the prime example of Dynamic or Late Binding
]]>
https://java2blog.com/difference-between-early-binding-and-late-binding-java/feed/ 1
Can we overload main method in java https://java2blog.com/can-we-overload-main-method-java/?utm_source=rss&utm_medium=rss&utm_campaign=can-we-overload-main-method-java https://java2blog.com/can-we-overload-main-method-java/#respond Fri, 03 Nov 2017 19:43:13 +0000 https://www.java2blog.com/?p=4380 In this post, we will see about "Can we overload main method in java".This is one of the most asked Core java interview questions.

Yes, we can overload main method in java but when you run your program, JVM will search for public static void main(String[] args) and execute that method.

Overload main method in java

For example:

package org.arpit.java2blog;

public class OverloadTestMain {
    public static void main(String[] args) {
        System.out.println("Inside main(String[] args)");
    }
    public static void main(Integer arg1) {
        System.out.println("Inside main(Integer arg1)");
    }

    public static void main(Integer[] arr) {
        System.out.println("Inside main(Integer array)");
    }
}

When you run above program, you will get below output.

Inside main(String[] args)

As you can see, we have overloaded main method but still, JVM calls the method with signature public static void main(String[] args).

Please note that JVM considers var args public static void main(String…args) same as public static void main(String[] args).

If you want to call overloaded method, then you need to call it from main method with signatute public static void main(String[] args).
For example:

package org.arpit.java2blog;

public class OverloadTestMain {
    public static void main(String[] args) {
        System.out.println("Inside main(String[] args)");
        main(2);
        main(new Integer[] {1,2,3});
    }

    public static void main(Integer args) {
        System.out.println("Inside main(Integer args)");
    } 

    public static void main(Integer[] arr) {
        System.out.println("Inside main(Integer arr)");
    }
}

When you run above program, you will get below output.

Inside main(String[] args)
Inside main(Integer args)
Inside main(Integer arr)

As you can see, we have called the overloaded methods from main method with String[] args.

That’s all about "Can we overload main method in java".

You can go through other interview questions about method overloading and method overriding.

]]>
https://java2blog.com/can-we-overload-main-method-java/feed/ 0
Dynamic method dispatch in java https://java2blog.com/dynamic-method-dispatch-java/?utm_source=rss&utm_medium=rss&utm_campaign=dynamic-method-dispatch-java https://java2blog.com/dynamic-method-dispatch-java/#respond Thu, 02 Nov 2017 17:19:06 +0000 https://www.java2blog.com/?p=4364 In this post, we will about Dynamic method dispatch which is also referred as run time polymorphism.

Dynamic Method Dispatch

Dynamic method dispatch is a technique by which call to a overridden method is resolved at runtime, rather than compile time.When an overridden method is called by a reference, then which version of overridden method is to be called is decided at runtime according to the type of object it refers.Dynamic method dispatch is performed by JVM not compiler.
Dynamic method dispatch allows java to support overriding of methods and perform runtime polymorphism.It allows subclasses to have common methods and can redefine specific implementation for them.This lets the superclass reference respond differently to same method call depending on which object it is pointing.

Base b=new Base();
Derived d=new Derived();
b=new Derived();      //Base class reference refer to derived class object  that is upcasting

When parent class reference variable refers to a child class object than its called upcasting and using this technique dynamic method dispatch perform.
We can not use derived class reference to refer to a base class object.
For example:

package org.arpit.java2blog;

class Rectangle
{
    int l=8,b=4;
    int area;
    public void area()
    {
        area=l*b;
        System.out.println("Area of rectangle: "+area);
    }
}
class Square extends Rectangle
{
    public void area()   //overridden method
    {
        area=l*l;
        System.out.println("Area of square: "+area);
    }
}
class Triangle extends Rectangle
{

    public void area()     //overridden method
    {
        area=(b*l)/2;
        System.out.println("Area of triangle: "+area);
    }
}
public class Calculation
{
    public static void main(String args[])
    {
        Rectangle r=new Rectangle();
        r.area();
        r=new Square();       //superclass reference referring to subclass Square object so,at run time it will call Square area()
        r.area();
        r=new Triangle();    //superclass reference referring to subclass Triangle object so,at run time it will call triangle area()     
        r.area();

    }
}

When you run above program, you will get below output.
Output:-

Area of rectangle: 32
Area of square: 64
Area of triangle: 16

That’s all about Dynamic method dispatch in java.

]]>
https://java2blog.com/dynamic-method-dispatch-java/feed/ 0
Can we override static method in java https://java2blog.com/java-override-static-method/?utm_source=rss&utm_medium=rss&utm_campaign=java-override-static-method https://java2blog.com/java-override-static-method/#respond Sun, 29 Oct 2017 18:16:49 +0000 https://www.java2blog.com/?p=4323 No, we can not override static method in java. Static methods are those which can be called without creating object of class,they are class level methods.

On other hand,If subclass is having same method signature as base class then it is known as method overriding. Its execution decided at run time.

Below are the reasons why we can’t override static method in java:-

  • Static methods are those which belong to the class.They do not belong to the object and in overriding, object decides which method is to be called.
  • Method overriding occurs dynamically(run time) that means which method is to be executed decided at run time according to object used for calling while static methods are looked up statically(compile time).
package org.arpit.java2blog;

class  Display
{
    public static void hello()    //static method 
    {
        System.out.println("Hello...Good morning");
    }
}
class  DisplayMessage extends Display
{

    public static void hello()      //redefining of base class static method in derived class
    {
        System.out.println("Hello...everyone");
    }
}
public class DisplayMsg
{
    public static void main(String args[])
    {
        Display d=new Display();     //creation of base class object
        d.hello();

        d=new DisplayMessage();    
        //base class reference is referring to derived class object and as per overriding rules it should call DisplayMessage hello()

        d.hello();       //but it calls Display class hello()

        DisplayMessage ds=new DisplayMessage();   //creation of derived class object
        ds.hello();
    }
}

When you run above program, you will get below output.
Output:

Hello…Good morning
Hello…Good morning
Hello…everyone

As per the rules of method overriding, method call is resolved at run time by the type of object.So, in our above example d.hello() in second example should call hello() method of DisplayMessage class because reference variable of Display class is referring an object of DisplayMessage but it call Display class hello() itself.This happens because static method is resolved at compile time.

So If derived class’s static method have same signature as base class’s static method, it is called method hiding not method overriding.

]]>
https://java2blog.com/java-override-static-method/feed/ 0
Copy Constructor in java https://java2blog.com/copy-constructor-java/?utm_source=rss&utm_medium=rss&utm_campaign=copy-constructor-java https://java2blog.com/copy-constructor-java/#respond Sat, 26 Aug 2017 16:34:23 +0000 http://www.java2blog.com/?p=3517 In this post, we will see about copy constructor in java.

Copy constructor is the constructor which takes parameter as object of same class and copy each field of the class to the new object. Unlike C++, java does not provide default copy contructor. You need to create one, if you want to have copy constructor in your class.Copy constructor is alternate to clone method.

Let’s say you have class name Country, so copy constructor will look like below:

public Country(Country countryObj)
{
     // Manually copying each field of country class
}

Java Copy Contructor

Copy constructors are used to create duplicate objects or cloned objects.Newly created object will have same characteristics as the original object. We need to be very careful while using Copy constructor because it is the responsibility of programmer to ensure that newly created object refers to different memory location than original. If you are confused here, don’t worry, I will explain you this with the help of an example.

Let’s understand use of Copy constructor with the help of simple example.
Create a class name capital.java as below:

package org.arpit.java2blog;

public class Capital {
    String capitalName;
    long population;

    public Capital(String name, long population) {
        super();
        this.capitalName = name;
        this.population = population;
    }
    public String getCapitalName() {
        return capitalName;
    }
    public void setCapitalName(String name) {
        this.capitalName = name;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }   
}

Create another class as Country.java. Please note that Country has a reference to above capital class.

package org.arpit.java2blog;

public class Country {

    String name;
    long population;
    Capital capital;

    public Country(String name, long population,Capital capital) {
        super();
        this.name = name;
        this.population = population;
        this.capital=capital;
    }

    // Copy constructor
    public Country(Country c) {
        super();
        this.name = c.name;
        this.population = c.population;  
        this.capital=c.capital;  // Shallow copy
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }

    public Capital getCapital() {
        return capital;
    }

    public void setCapital(Capital capital) {
        this.capital = capital;
    }   
}

Let’s create main class named "CopyConstructorMain.java"

package org.arpit.java2blog;

public class CopyConstructorMain {

    public static void main(String[] args) {
        // Create capital object
        Capital capital=new Capital("Delhi", 10000);

        // Create country object
        Country countryIndia=new Country("India", 90000,capital);

        // Use copy constructor to create duplicate object
        Country countryIndiaCopied=new Country(countryIndia);

        System.out.println("Country name of Copied object: "+countryIndiaCopied.getName());
        System.out.println("Country population of Copied object: "+countryIndiaCopied.getPopulation());
        System.out.println("Capital name of Copied object: "+countryIndiaCopied.getCapital().getCapitalName());
        System.out.println("Capital population of Copied object: "+countryIndiaCopied.getCapital().getPopulation());

        System.out.println("============================================");

                // Changing capital name of original object
        countryIndia.getCapital().setCapitalName("Mumbai");
        System.out.println("Capital name of Original object: "+countryIndia.getCapital().getCapitalName());
        System.out.println("Capital name of Copied object: "+countryIndiaCopied.getCapital().getCapitalName());
    }
}

When you run above program, you will get below output:

Country name of Copied object: India
Country population of Copied object: 90000
Capital name of Copied object: Delhi
Capital population of Copied object: 10000
============================================
Capital name of Original object: Mumbai
Capital name of Copied object: Mumbai

We are able to copy all content of countryIndia to countryIndiaCopied. That’s great!!
But did you notice an issue here? When we changed capital name in original object, it got changed in duplicate object too.This is because we have done shallow copy in case of capital object, so both objects are referring to same capital reference.You need to be careful while using copy constructor as it may result in unexpected behavior and it is very hard to debug.

Let’s create a deep copy in copy constructor of the Country class and it should fix above issue.
Introduce a copy constructor in Capital class and use it in copy constructor of the Country class.
Capital.java

package org.arpit.java2blog;

public class Capital {
    String capitalName;
    long population;

    public Capital(String name, long population) {
        super();
        this.capitalName = name;
        this.population = population;
    }

    // Copy constructor
    public Capital(Capital oldCapital) {
        this.capitalName = oldCapital.capitalName;
        this.population = oldCapital.population;
    }

    public String getCapitalName() {
        return capitalName;
    }
    public void setCapitalName(String name) {
        this.capitalName = name;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }
}

Country.java

package org.arpit.java2blog;

public class Country {

    String name;
    long population;
    Capital capital;

    public Country(String name, long population,Capital capital) {
        super();
        this.name = name;
        this.population = population;
        this.capital=capital;
    }

    // Copy constructor
    public Country(Country c) {
        super();
        this.name = c.name;
        this.population = c.population;  
        this.capital=new Capital(c.capital);  // Deep copy
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }

    public Capital getCapital() {
        return capital;
    }

    public void setCapital(Capital capital) {
        this.capital = capital;
    }

}

Now you execute CopyConstructorMain.java, you will get below output:

Country name of Copied object: India
Country population of Copied object: 90000
Capital name of Copied object: Delhi
Capital population of Copied object: 10000
============================================
Capital name of Original object: Mumbai
Capital name of Copied object: Delhi

As you can see here, when we made changes to capital name of original object, it did not impact copied object.

If you have mutable object in the class then you need to take care of it by doing deep copy while creating duplicates.Otherwise, it may result in unexpected behaviour.

that’s all about copy constructor in java.

]]>
https://java2blog.com/copy-constructor-java/feed/ 0
Java default constructor https://java2blog.com/java-default-constructor/?utm_source=rss&utm_medium=rss&utm_campaign=java-default-constructor https://java2blog.com/java-default-constructor/#respond Sat, 26 Aug 2017 16:32:16 +0000 http://www.java2blog.com/?p=3522 In this post, we will see about Java default constructor.
Default constructor is the no arg constructor which is inserted by compiler unless you provide any other constructor explicitly.
You won’t able to see it as it is present in class file rather than source file.

Is there any difference between no argument constructor and default constructor?

If you provide any constructor in class, it’s no longer default constructor.There is lots of debate on it but it is my opinion.
When you do not provide any constructor, compile will insert default constructor which will call super class’s default constructor.You need to make sure that super class has no-arg constructor.

Let’s understand this with the help of an example
Create a class named Person.java

package org.arpit.java2blog.constructor;

public class Person {

    String name;
    int age;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Create another class named Employee.java

package org.arpit.java2blog.constructor;

public class Employee extends Person {

    int empId;

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }
}

You will get compilation error at line with this message.
"Implicit super constructor Person() is undefined for default constructor. Must define an explicit constructor"
As you can see here, it tells you that Person class should have explicit constructor else it won’t compile.
Once you add no arg constructor to Person class, you won’t get compilation error anymore.

package org.arpit.java2blog.constructor;

public class Person {
    String name;
    int age;

        // Added explicit constructor
    public Person()
    {
        System.out.println("Added explicit constructor");
    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

As you can see once you add explicit constructor to Person class, there won’t be any compilation error in Employee class.
That’s all about default constructor in java.

]]>
https://java2blog.com/java-default-constructor/feed/ 0
Inheritance in Java https://java2blog.com/inheritance-java/?utm_source=rss&utm_medium=rss&utm_campaign=inheritance-java https://java2blog.com/inheritance-java/#comments Thu, 27 Jul 2017 19:28:36 +0000 http://www.java2blog.com/?p=3255 In this post, we will see about Inheritance in java. It is one of the OOPs principles apart from Abstraction, encapsulation and polymorphism.

Introduction

The word Inheritance is quite familiar with everyone. In common terms, the word means the bequeathing of property and characteristics from generation to generation. For example, the property or characteristics of parents are handed down to their children and the forthcoming generations.

Object Oriented Programming (commonly OOP) concepts are based on real life examples, where every entity in existence can be represented as an object. Thus, being one of the fundamental concepts in OOP, Inheritance is based on the example we discussed earlier – bequeathing of properties and characteristics from parents to their children.
Inheritance in Java, as derived from the concept of OOP, is defined as the process by which a child class or object (known as subclass) inherits the behaviors and properties(methods and variables) from its predecessors or parent class(known as super class). Let us delve a little deeper into the concepts of Inheritance in java with the following sections.

Basic Syntax

Inheritance in Java is implemented by the use of the keyword extends. This special word makes the Java compiler understand that the current class is inheriting or extending another class. Let us look at the following snippet example to understand the basic syntax.

public class B extends A {

// some process or variables

}

The above snippet shows the use of the extends keyword. In the language of Java, the use of ‘extends’ indicates that the class B is a child or a subclass of the class A, which is known as the super class or parent. Inheritance represents an IS-A relationship between classes. Here, B is a child or subclass of A.

Example of Inheritance in Java

Inheritance

The picture given alongside displays a simple representation of inheritance in Java.
Here, the class Parent contains an integer variable a and is a super-class to class Child which contains an integer variable b
Let us see the representation of this picture by means of a code example.

class Parent {

 int a = 5;
}

class Child extends Parent {
 int b= 7;
 public static void main(String args[]){
   Child c = new Child();
   System.out.println(“Value of A =”+c.a);
   System.out.println(“Value of B =”+c.b);
   System.out.println(“Sum=”+(c.a+c.b));
 }
}

The above code snippet on execution, provides the following result:

Value of A =5
Value of B =7
Sum=12

From the above sample we see that the child class B is able to access the variable a of class Parent and use it in its own class. Thus we see that using inheritance, sub-classes may utilize variables and methods from their super-classes.

Types of Inheritance in Java

There are various forms of representing a Parent-Child relationship in Object Oriented Programming. Java supports three types of Inheritance on the basis of classes. The various types of inheritance shall be discussed further in this section and how they are realized using Java.

Single Inheritance

This is the simplest form of inheritance in Java and is a simple ONE to ONE relationship between two classes. A basic example of single inheritance has already been discussed in the section above, where a single Child class had inherited the attributes of its Parent class.

Single Inheritance

The picture given alongside represents a single inheritance between classes A(super-class) and B(sub-class)
Let us see a small code snippet as an example of Single Inheritance.
Code:

class MessageWriter {
   public void display(){
   System.out.println(“You are viewing a method of A”);
   }
}

class MessageDisplayer extends MessageWriter {
     public static void main(String args[]) {
         B obj=new B();
         obj.display();
    }
}

The above code snippet executes to produce the following output:

You are viewing a method of A

Multi-Level Inheritance

Multi-Level Inheritance as its name suggests looks more like a tier-based structure. The picture given alongside represents a multi-level inheritance structure. In Multi-Level Inheritance, each class extends only a single class in the form of a multi-level or multi-tiered architecture.

For instance, from the figure alongside, we see that class C is a sub-class of class B and class B is a sub-class of class A. Thus, B will inherit the attributes and behavior of class A and C, in turn, will inherit from both.
Let us see a code snippet as an example of Multi-Level Inheritance.

class Animal {
    void eat(){
      System.out.println(“Animals eat”);
  }
}

class Horse extends Animal {
  void call(){
     System.out.println(“Horses neigh”);
  }
}

class Colt extends Horse {
   void desc(){
     System.out.println(“Colts are baby horses”);
  }
}

class TestMultiLevel {
    public static void main(String args[]){
        Colt c = new Colt();
        c.desc();
        c.call();
        c.eat();
    }
}

On executing the above code, the following output is obtained:

Colts are baby horses
Horses neigh
Animals eat

Hierarchical Inheritance

Hierarchical Inheritance is a type of inheritance where many sub-classes extend a single super-class.

Hierarchical Inheritance

The picture given alongside represents a basic form of Hierarchical Inheritance. This form of inheritance is basically multiple single inheritances where all sub classes inherit from a single super class. Here, classes B and C are sub-classes of class A and inherit its attributes and behavior.
Let us see a code snippet as an example of Hierarchical Inheritance.
Code:

class Animal {
  void eat(){
    System.out.println(“Animals eat”);
 }
}

class Lion extends Animal {
   void call(){
   System.out.println(“Lions roar”);
  }
}

class Wolf extends Animal {
   void call(){
    System.out.println(“Wolves howl”);
 } 
}

class TestHierarchy{
public static void main(String args[]){
     Wolf w = new Wolf();
     Lion l=new Lion();
     w.call();
     w.eat();
    l.call();
    l.eat();
  }
}

The above code, on execution, produces the following output:

Wolves howl
Animals eat
Lions roar
Animals eat

Multiple and Hybrid Inheritance

Multiple Inheritance is a type of Inheritance in Object Oriented Programming where a single sub-class extends multiple super-classes. Hybrid Inheritance is a mixed form of inheritance comprising of Multiple and Multi-Level Inheritance. Multiple Inheritance is not supported by Java.

Multilevel inheitance

Above picture shows Multiple Inheritance

Hybrid inheritance

This picture depicts Hybrid Inheritance.

Why does Java not support Multiple Inheritance?

To reduce complexity and ambiguity, Java does not allow Multiple Inheritance using classes. Let us explain the ambiguity with an example.
Say, there is a class A having a method display() and class B having another method display(). A third class C, extends both A and B and as per the concept of inheritance, is able to access both the display() methods of A and B. Now, when creating an object of C and calling the display() method, the compiler will not be able to discern which display method to call as both classes A and B have a method having the same name and are extended by class C.

Code:

Class A (){
    public void display ()
    {
     //some code
    } 
}
class B (){
  public void display ()
  {
   //some code 
  } 
}
class C extends A,B () ( Not supported in Java ){
public static void main (){
  C obj = new C ();
  obj.display(); ( Ambiguity between display() of class A and display of class B)
 }
}

In order to prevent this ambiguity, Java does not allow multiple inheritance between classes and throws a compile-time error when multiple inheritance is attempted.
Note: Java, however, simulates Multiple Inheritance by using Interfaces.

Conclusion

Inheritance is a strong weapon of Java that helps to make it a widely acceptable language. It helps to reduce code duplication and also cuts down on the bugs. With the code written in the parent class, you no longer need to write the same code for multiple child classes that has the same properties. In this way, inheritance in java implements code reusability to ensure better accessibility to users.

That’s all about inheritance in java.

]]>
https://java2blog.com/inheritance-java/feed/ 1
Constructor in java https://java2blog.com/constructor-java/?utm_source=rss&utm_medium=rss&utm_campaign=constructor-java https://java2blog.com/constructor-java/#comments Sat, 27 May 2017 19:05:37 +0000 http://www.java2blog.com/?p=2686 Constructor in java is block of code which allows you to create instance of the object. It does not have return type.
It has two main points

  • Constructor name should be same as class
  • Constructor should not have any return type else it will be same as method.

There are three types of Constructor in Java.

  • Default Constructor
  • No arg constructor
  • Parameterized constructor

How to call a constructor?

To call a constructor, you need to use the keyword new, followed by the name of class, followed by parameters if any.
For example: If you want to create the object of class Employee, you can call the constructor like this: new Employee()

Types of Contructor

Default Constructor:

When you do not provide the constructor for your class, JVM will create default constructor.It will not be visible to you, JVM will create it automatically while initializing object of the class.

Let’s check with the example of example:

package org.arpit.java2blog;

public class Employee {

    String name;
    int age;

    public void workOnAssignment()
    {
        // Working on assignment
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String args[])
    {
        Employee e1=new Employee();
        e1.setName("John");
        e1.setAge(20);
        System.out.println(e1.getName());
        System.out.println(e1.getAge());
    }
}

As you can see here, we did not provide any constructor for this class but JVM will create default constructor in this case.
When you run above program, you will get below output:

John 20

no arg construtor

no arg constructor is constructor which you provide explicitly in the class and it does not have any argument.

package org.arpit.java2blog;

public class Employee {

    String name;
    int age;

    public Employee()
    {
        System.out.println("Calling no arg constructor");
    }
    public void workOnAssignment()
    {
        // Working on assignment
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String args[])
    {
        Employee e1=new Employee();
        e1.setName("John");
        e1.setAge(20);
        System.out.println(e1.getName());
        System.out.println(e1.getAge());
    }
}

When you call above program, you will get below output:

Calling no arg constructor
John
20

Parameterized constructor

When you pass arguments to the constructor, this type of constructor is called Parameterized constructor.

package org.arpit.java2blog;

public class Employee {

    String name;
    int age;

    public Employee(String name,int age)
    {
        System.out.println("Calling Parameterized constructor");
        this.name=name;
        this.age=age;       
    }
    public void workOnAssignment()
    {
        // Working on assignment
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String args[])
    {
        Employee e1=new Employee("John",20);
        System.out.println(e1.getName());
        System.out.println(e1.getAge());
    }
}

When you run above program, you will get below output:

Calling Parameterized constructor
John
20

If you provide Parameterized Constructor,then you need to be careful.
Let’s see below program:

package org.arpit.java2blog;

public class Employee {

    String name;
    int age;

    public Employee(String name,int age)
    {
        System.out.println("Calling Parameterized constructor");
        this.name=name;
        this.age=age;       
    }
    public void workOnAssignment()
    {
        // Working on assignment
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String args[])
    {
        Employee e1=new Employee();
        e1.setName("John");
        e1.setAge(20);
        System.out.println(e1.getName());
        System.out.println(e1.getAge());
    }
}

If you notice, you will get compilation error at line no.38. Why so?
because if you create parameterized constructor in class, JVM won’t provide default constructor to you. If you do not write any constructor then only JVM will provide you default constructor.

Constructor chaining

Constructor chaining is the concept where child class calls the constructor of its parent class internally or explicitly.
Whenever you create an object in Java, its superclass constructor gets called. The compiler simply put super() in the constructor internally.
Let’s see with help of example:
Let’s say you have Person class with attribute name and you have child class named Employee which extends Person class.

package org.arpit.java2blog;

public class Person
{
    String name;
    public Person()
    {
        System.out.println("Calling Person constructor");
        name="John";
    }
}
class Employee extends Person{

    int age;

    public Employee()
    {
        System.out.println("Calling Employee class constructor");
        name="Martin";
    }
    public void workOnAssignment()
    {
        // Working on assignment
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String args[])
    {
        Employee e1=new Employee();

        System.out.println(e1.getName());
    }
}

When you run above program, you will get below output:

Calling Person constructor
Calling Employee class constructor
Martin

As you can see here, First Person constructor got called and it set name variable to John
Then Employee constructor got called which have overridden name variable to Martin.
That’s why we see a variable name as "Martin" in the end.

What if you want to explicitly call super class parameterized constructor

You can easily do it using super keyword.
Let’s see with the help of Example.

package org.arpit.java2blog;

public class Person
{
    String name;
    public Person(String name)
    {
        this.name=name;
        System.out.println("Calling Person Parameterized constructor");
    }
}
class Employee extends Person{

    int age;

    public Employee(String name)
    {
        super(name);
        System.out.println("Calling Employee class constructor");
    }
    public void workOnAssignment()
    {
        // Working on assignment
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String args[])
    {
        Employee e1=new Employee("John");

        System.out.println("Employee's name:"+e1.getName());
    }
}

When you run above program, you will get below output:

Calling Person Parameterized constructor
Calling Employee class constructor
Employee’s name:John

What if you want to call another constructor of same class

If you want to call overloaded constructor of same class, you can use this keyword to do that.
For example:

package org.arpit.java2blog;

public class Employee {

    String name;
    int age;

    public Employee() {
        System.out.println("Calling No arg constructor");
    }

    public Employee(String name,int age)
    {
        this();
        System.out.println("Calling Parameterized constructor");    
        this.name=name;
        this.age=age;       
    }

    public void workOnAssignment()
    {
        // Working on assignment
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String args[])
    {
        Employee e1=new Employee("John",20);
        System.out.println("Employee's name : "+e1.getName());
        System.out.println("Employee's age : "+e1.getAge());
    }
}

When you run above program, you will get below output:

Calling No arg constructor
Calling Parameterized constructor
Employee’s name : John
Employee’s age : 20

Please note that this keyword used for calling overloaded constructor should be first statement in that constructor.

that’s all about Constructor in Java.

]]>
https://java2blog.com/constructor-java/feed/ 1
Polymorphism in java with example https://java2blog.com/polymorphism-java-example/?utm_source=rss&utm_medium=rss&utm_campaign=polymorphism-java-example https://java2blog.com/polymorphism-java-example/#respond Sat, 27 May 2017 17:49:37 +0000 http://www.java2blog.com/?p=2689 In this tutorial, we will see about Polymorphism in java.

Polymorphism in java is one of core Object oriented programming concepts with Abstraction, encapsulation, and inheritance.

Polymorphism means one name many forms. In Java, polymorphism can be achieved by method overloading and method overriding.

There are two types of polymorphism in java.

  • Compile time polymorphism.
  • Run time polymorphism.

Compile time Polymorphism

Compile time Polymorphism is nothing but method overloading in java. You can define various methods with same name but different method arguments. You can read more about method overloading.

Let’s understand with the help of example:

package org.arpit.java2blog;

public class MethodOverloadingExample {
    public void method1(int a)
    {
        System.out.println("Integer: "+a);
    }
    public void method1(double b)
    {
        System.out.println("Double "+b);
    }
    public void method1(int a, int b)
    {
        System.out.println("Integer a and b:"+a+" "+b);
    }
    public static void main(String args[])
    {
        MethodOverloadingExample moe=new MethodOverloadingExample();
        moe.method1(20);
        moe.method1(30.0);
        moe.method1(20, 30);
    }
}

When you run above program, you will get below output:

Integer: 20
Double 30.0
Integer a and b:20 30

As you can see here, we have used same method name but different method arguments.The compiler will call appropriate method based on best-matched arguments.

Runtime Polymorphism

Runtime Polymorphism is nothing but method overriding in java.If subclass is having same method as base class then it is known as method overriding Or in another word, If subclass provides specific implementation to any method which is present in its one of parents classes then it is known as method overriding.

Let’s say you have parent class as Shape and child class as Rectangle and circle.

package org.arpit.java2blog;

public class Shape {

    public void draw()
    {
        System.out.println("Drawing Shape");
    }
    public static void main(String[] args) {
        Shape s=new Rectangle();
        s.draw();

        s=new Circle();
        s.draw();
    }

}
class Rectangle extends Shape
{
    public void draw()
    {
        System.out.println("Drawing Rectangle");
    }
}

class Circle extends Shape
{
    public void draw()
    {
        System.out.println("Drawing Circle");
    }
}

When you run above program, you will get below output:

Drawing Rectangle
Drawing Circle

Please note that we are assigning child object to parent object here.

Shape s=new Rectangle();

As you can see we have overridden draw methods in child class Rectangle and Circle.JVM decides at runtime which method it needs to call depending on the object assignment. That’s why this is known as Run time polymorphism.

That’s all about Polymorphism in java.

]]>
https://java2blog.com/polymorphism-java-example/feed/ 0