Pages

Thursday, 21 February 2013

SCJP exam. The most common "Compilation fails" questions-2

no default constructor in a superclass

class One{
    String s;
    One(String s){
        this.s = s;
    }
}
class Two extends One{
    Two(String s){
                   // problem 
        this.s = s;
    }
}
interface implementation (method signature)
class Persons{
    String name;
    Persons(String name){
        this.name = name;
    }
    public String toString() {
        return this.name;
    }
}
interface Personable {
    Persons getPerson(String name);
}
class MyPerson implements Personable{
    Persons getPerson(String name) { // problem (must be public)
        return new Persons(name);
    } 
    public static void main(String[] args){
        List ps = new ArrayList();
        MyPerson m = new MyPerson();
        for (int i = 100; i++ < 102; ps.add(m.getPerson("" + i)));
        for(Object o:ps) System.out.println(o);
    }
}


method signature

class myThread extends Thread {
    public static void main(String[] args) {
        Thread t = new Thread(new myThread());
        t.start();
    }
    public static void run() { //problem (must not be static)
        for(int i = 0; i < 2; i++)
            System.out.print(Thread.currentThread().getName() + " ");
    }
}
instance variable hasn't been created yet

class Game {
    static String s = "-";
    String s2 = "s2";
    Game(String arg) { 
        s += arg; 
    }
}
class Go extends Game {
    { s += "i "; }
     Go() { super(s2); } // problem
    public static void main(String... args) {
        new Go();
        System.out.println(s);
    }
    static { s += "sb "; }
}
local variable is accessed from within inner class needs to be declared final

class LocalVarTest{
    public static void main(String[] args) {
        int x = 10;
        class Inner{
            void printIt(){
                System.out.println(x); // problem
            }
        }
        Inner inner = new Inner();
        inner.printIt();
    }
}
and so on...

No comments:

Post a Comment