Google

Mar 19, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 3



Q8: What will be the statement you add so that you invoke Abc's process( ) method?


package com.writtentest5;

public class Abc {

 public void process(){
    System.out.println("Processing Abc");
 }

}



package com.writtentest5;

public class Def extends Abc {
 
 public void process(){
    System.out.println("Processing Def");
    ___________________________________ //how will you invoke Abc's process method here?
 }
 

 public static void main(String[] args) {
    Abc myApp = new Def();
    myApp.process();
 }

}




A8: super.process( ) will invoke parent class's process( ) method.


Q9: Which of the following interfaces will you be concerned about when adding an object to a HashSet?


a) Collection
b) Set
c) SortedSet
d) List
e) All the above

A9: Answer is a and b.

The Set interface extends the Collection interface, and HashSet implements the  Set  interface. Hence a and b are correct. You can write either

Collection<String> col = new HashSet<String>();
col.add("a");

or

Set<String> col = new HashSet<String>();
col.add("a");


Coding to an interface is a best practice.

c) is wrong because the SortedSet is implemented by ConcurrentSkipListSet and TreeSet. if you write

SortedSet<String> col = new HashSet<String>();
col.add("a");


you will get a compile time error "Type mismatch"

If you write as

SortedSet<String> col = (SortedSet)new HashSet<String>();
col.add("a");


you will get a Runtime exception

Exception in thread "main" java.lang.ClassCastException: java.util.HashSet cannot be cast to java.util.SortedSet
at com.writtentest5.Def.main(Def.java:19)


Note: There are a number of Set implementations listed below, but their behaviors are quite different.

  • java.util.EnumSet
  • java.util.HashSet
  • java.util.LinkedHashSet
  • java.util.TreeSet


You may also like





Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home