Me and my fellow students (1st year CS) are struggling with the issue classes and sub-classes. We have a test, in which one of the questions checks the understanding of Classes, sub-classes, Legal and illegal casting between them etc. The questions are usually the same: You are given 2-3 classes named A,B,C, some of them extend others, and then different constructors and a 10-15 very confusing lines of code, on each of them we need to tell if it will cause one of the following: 1. Run-time error. 2. Compilation error. 3. Will run (what will be printed out).
The test is paper only. The question is, do you have a method of tracking the different classes and variables? is there a site that teaches these subjects?
This is the question from the previous test: Which of the following lines of code will cause Compilation error, runtime error, and what will be printed: (I added the solution)
A a = new A(1,2);
B b = new B(1,2,3);
C c = new C(1,2);
A bb = (A) b;
A a1;
A a2 = null;
System.out.println("Hello world"); //"Hello World
System.out.println(Hello world); //Compilation error
System.out.println(1/0); //Runtime Error
a = b; //Will run with no errors
a.equals(a1); //compilation error
System.out.println(a.equals(a2));//will print false.
System.out.println(b.equals(c)); //will print true.
B aa = (B) a; //runtime error.
C bbb = (C) bb; //runtime error
C ccc = (C) b; //compilation error
a.m1(); //will print m2
b.m1(); //will print 3
c.m3(); //will print 2.
a.m5(); //will print false
Class A:
public class A {
private int x;
public int y;
private C c = null;
public A(int x,int y){
this.x = x;
this.y = y;
}
public void m1() { m2();}
public void m2() {
System.out.println("m2");
}
public void m3(){ m4(); }
public void m4() {
A tmp = new B(1,2,3);
System.out.println(tmp.y);
}
public void m5() {
System.out.println((new C().equals(c)));
}
public boolean equals(Object other) {
if(!(other instanceof A)) return false;
return (((A)other).x==x &
((A)other).y==y);
}
}
Class B:
public class B extends A {
public int y;
public B(int x, int y1, int y2){
super(x,y1);
this.y = y2;
}
public void m2(){
m3();
}
public void m4() {
B temp = new B(1,2,3);
System.out.println(temp.y);
}
}
Class C:
public class C extends A {
public int y;
public C(int x, int y){
super(x,y);
this.y = y;
}
public C(){
this(0,0);
}
}
I know it is long, but I wanted you to understand the type of the questions... I'm not looking for the answers, try to help me understand the concepts and the ways to think this through. The main issues we are struggling with are with when you extend one class, then call a method within it, that calls a different method in a subclass and so and so.... Tracking all that is difficult. Thank's a lot, Barak