Menu
Topics Index
...
`

Genericinterfaces2854


If you need explanation Read this topic

If you need Answer Take test on this topic

Genericinterfaces2854
What will be the output of the following program?
public class BoxAndBottle {
    public static void main(String[] args) {
        Box a = new Box();
        a.add(10);
        System.out.println(a.get());
        Bottle b = new Bottle();
        b.add("Hello");
        System.out.println(b.get());
    }
}
interface a<T> {
    public void add(T t);
}
class Box implements a<Integer> {
    int t;
    public void add(Integer t) {
        this.t = t;
    }
    public int get() {
        return t;
    }
}
class Bottle implements a<String> {
    public String get() {
        return "Hai";
    }
}

A. 10
Hai
B. 10
Hello
C. Some other output
D. Compilation Error or Runtime Error
Topic: Generic Interface In Java

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.

Answer is D Compilation error as Class Bottle is not implementing the add method in interface.Class that implements any interface must define all the methods of that interface

Posted by Shashanka Mogaliraju    2014-10-20 12:12:57


ans is d.
because compiler cannot find
symbol
b . add ( "Hello" );
  symbol:   method add(String)
  location: variable b of type Bottle
Bottle is not
abstract and does not override
abstract method add(String) in a
class Bottle implements a < String>
{
}
hence there will be two error arises..

Posted by Shubham Bansal    2014-10-20 13:13:46


Ans is D..

here concept dealing with generic interfaces..interface is similar type of class which contains all abstract methods,the class which implements interface must define all methods of interface otherwise the class must delcared as abstract Bcz wen you implement all methods wil come into class if u didnt overide a method than it wil be lyk abstract method in your class if class contains abstract method than class must b declared as abstract

here class Box and Bottle implementing the Interface a as Integer and Bottle as String, we can take any type Bcz interface is generic type, even we can  have Bounded Generics for the interface

Box is overriding the method add() but class Bottle is not defining the method add() and didnt declared as abstract compiler wil give an error

we are calling add() by using the Bottle Object Bottle class does not contains that method so compiler wil raise error even here

Posted by Uday Kumar    2014-10-20 14:51:05


This dose is now closed and the winners are Shashanka Mogaliraju,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Šâí Râm for the 'Popular Comment'. The 'lucky liker' is Varun Kumar. 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-10-21 04:23:03


© meritcampus 2019

All Rights Reserved.

Open In App