Menu
Topics Index
...
`

Generics Upper Bounded Wildcard


If you need explanation Read this topic

If you need Answer Take test on this topic

Generics Upper Bounded Wildcard
What will be the output of the following program?
public class GenericsWildCardsDemo {
    public static void main(String args[])
    {
        Variables<Integer> obj = new Variables<Integer>(5, 8);
        print(obj);
    }
    public static void print(Variables<? extends Number> var)
    {
        System.out.println(var.getAddition());
    }
}
class Variables<T extends Number>
{
    T x;
    T y;
    Double sum = 0.0;
    public Variables(T x, T y) {
        this.x = x;
        this.y = y;
    }
    public Double getAddition()
    {
        sum+= x.doubleValue() + y.doubleValue();
        return sum;
    }
}

A. 0.0
B. 13.0
C. Compilation Error
D. Runtime Error
Topic: Generics Wildcards In Java With Examples

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans is C ,,int can't be dereferenced

Posted by Raju VarshnEy    2014-11-06 12:15:00


ans b.variable class object created. it extends number class.print() calld obj passed as an argument.getadditin method return addition of 5,8 integer object. double Value () extracts primitive double value frm integer object

Posted by Maheshwari Natarajan    2014-11-06 12:39:41


Ans is B...here we have UpperBound wild cards which is used to restrict the unknown specific type,it must me child class of the Specified class.... ? extends Number means...any sub class of the Number...here we create Object for the variable class with Integer class here it is acceptable Bcz it is an chikd of the number...next we are calling the print method by passing the created Object..in this we are calling the getAddition()) there we are  adding x and y to sum and than returing the sum value which is Double...than it wil 8.0+5.0=13.0

Posted by Uday Kumar    2014-11-06 13:34:17


This dose is now closed and the winners are Maheshwari Natarajan,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Maheshwari Natarajan. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-11-07 04:27:39


© meritcampus 2019

All Rights Reserved.

Open In App