Posts

Showing posts from 2019

Java 5: Covariant Return Type

Before Java 1.5, when we override a Parent class method then we need to have same return type of method in child class.  From Java 5 onwards, we can override a method by changing its return type, but overriding method's return type should be a sub-type of overridden method return type. For example, class Parent {    public Parent getObject() {      return this;    } } class Child extends Parent {    public Child getObject() {      return this;   }    public void print() {      System.out.println("Child class method..!");   }   public static void main(String[] args){     new Child().getObject().print();   } }

Java 5: Varargs

Suppose you are creating a method, but you aren't sure how many arguments your method is going to accept. So, to address this problem var-args were introduced with Java 1.5 release.  Prior to Java 1.5, we need to create overloaded method to handle variable number of parameters.  Varargs is short name of variable length argument.  Syntax:  A variable-length argument is specified by three periods(…).  For Example, public static int sum(int ...i) {      // method body } Above syntax tells the compiler that the sum() method can take zero or more arguments of type int. class Test {  public static int sum(int ...i) {      int sum = 0;      for (int a: i)          sum+=a;      return sum;  }  public static void main(String []args){     System.out.println(sum(1,2,3));     System.out.println(sum());     System.out.println(sum(1,2));  } } Output: 6 0 3