Menu
Topics Index
...
`

Creating Generic Class Method and Variables1685


If you need explanation Read this topic

If you need Answer Take test on this topic

Creating Generic Class Method and Variables1685
What is the output of the following program?
import java.io.*;
class Gen<T> implements Serializable {
    T ob;
    public Gen(T ob) { this.ob = ob;  }
    T getOb() { return ob; }
}
class Gen2<T, U> extends Gen<T> {
    U os;
    public Gen2(T ob, U os) {
        super(ob); // LINE A
        this.os = os;
    }
    T getOb() { return ob; }
    U getOs() { return os; }
    public static U myMethod() { return os; }
}
public class Complex {
    public static void main(String[] args) {
        Gen<Integer> gen = new Gen<Integer>(50);
        Gen2<String, Integer> gen2 = new Gen2<String, Integer>("Merit Campus", 155);
        try {
            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("file.txt"));
            os.writeObject(gen);
            os.writeObject(gen2);
        } catch (Exception e) { System.out.println(e);  }
        try {
            ObjectInputStream os = new ObjectInputStream(new FileInputStream("file.txt"));
            gen = (Gen<Integer>) os.readObject();
            gen2 = (Gen2<String, Integer>) os.readObject();
        } catch (Exception e) { System.out.println(e); }
        System.out.print(gen.getOb() + " " + gen2.getOb() + " " + gen2.getOs() + " " +   Gen2.myMethod());
    }
}

A. 50 Merit Campus 155 Merit Campus
B. 50 Merit Campus 155
C. Compilation Error at LINE A since Gen is Integer type but we are passing String type
D. Compilation Error because of some other reason
E. NotSerializableException
Topic: Java ObjectInputStream

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 D....because in the declaration of myMethod() the return type is a generic and we placed a static keyword before it...so during compile time the generic value is not known so it results in a compilation problem!

Posted by Santosh Munugota    2013-08-08 12:43:30


D is the correct answer we will get compile time error because here while creating gen2 obj we are passing string and int as types but here we are calling super class constructor without knowing its type

Posted by Ram Reddy Bitla    2013-08-08 12:45:34


ans should be D bcoz we are tryin to use a static function wth a template which can be of any data type...as static functions are common to all objects bt data types r different for differnt objects it gives compilation error

Posted by Pramod Jain    2013-08-08 12:45:42


Congratulations Santosh Munugota. You are this dose winner. Please send us your mobile details and we will process the recharge asap.

Posted by Merit Campus    2013-08-09 03:38:16


got rc :)

Posted by Santosh Munugota    2013-08-12 17:08:22


© meritcampus 2019

All Rights Reserved.

Open In App