Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Download 1.52 Mb.
Pdf ko'rish
bet55/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   51   52   53   54   55   56   57   58   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

141.
142.
CHAPTER
13
Generics
What happens when you compile and run the following
code?
class Mammal {}
class Cat extends Mammal { }
List list = new ArrayList();
Answer:
This code will not compile. This is because Mammal is specified
for List while Cat is specified for ArrayList. The rule is that
the type of the variable declaration must match the type that you
specify for the implementation. So, the same data type needs to
be specified in the List and ArrayList.
Will Line 1 in the following line of code compile? If not,
state the reasons.
class Mammal {}
class Cat extends Mammal { }
List mList = new ArrayList(); //
line 1
Answer:
Line 1 will cause a compilation error. This is because Cat is at a
lower level of hierarchy than Mammal. Mammal is the super class.


143.
144.
145.
So, the above code will compile only if  is replaced with
 or .
Explain the issue with the following code.
List mylist = new ArrayList();
Answer:
The above line of code creates a List named mylist. It specifies
the wild card notation (? Symbol) in the List declaration. This is
incorrect and causes a compilation error because a wildcard
notation cannot be used in the declaration part. Wildcard
notations for generics are only allowed only in method
parameters or return values.
Explain what additional code is required to make the code
snippet below valid:
public void getList(T t)
Answer:
This code declares a method called getList() with a generic
argument. In order for this code to be valid, this method must be
inside a class that accepts a generic type as follows:
public class MyClass {
public void getList(T t){
}
}

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   51   52   53   54   55   56   57   58   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling