In: Computer Science
Consider the following code:
public class Bay extends Lake { public void method1() { System.out.println("Bay 1"); super.method2(); } public void method2() { System.out.println("Bay 2"); } } //********************************* class Pond { public void method2() { System.out.println("Pond 2"); } } //************************** class Ocean extends Bay { public void method2() { System.out.println("Ocean 2"); } } //********************************* class Lake extends Pond { public void method3() { System.out.println("Lake 3"); method2(); } } //**************************** class Driver { public static void main(String[] args) { Object var4 = new Bay(); Lake var5 = new Bay(); // the following lines of code are causing wither syntax or runtime error // var4.method2(); error 1 // ((Ocean) var5).method1(); error 2 } }
Answer the following question.
Identify the cause of the error is it run time error or syntax error.
Explain why the error is happening
provide code to fix the problem. Do not change the declaration or the instantiation to fix the issue.
class Bay extends Lake {
public void method1() {
System.out.println("Bay 1");
super.method2();
}
public void method2() {
System.out.println("Bay 2");
}
}
class Pond {
public void method2() {
System.out.println("Pond 2");
}
}
class Ocean extends Bay {
public void method2() {
System.out.println("Ocean
2");
}
}
class Lake extends Pond {
public void method3() {
System.out.println("Lake 3");
method2();
}
}
public class Driver {
public static void main(String[] args) {
Object var4 = new Bay();
Lake var5 = new Bay();
// the following lines of code
are causing wither syntax or runtime error
// Compile time error because here
var4 is reference of class Object so method4 does not have
declaration in class Object
// so we will get compilation
error
((Bay)var4).method2();
// Here the var5 is pointing to
Object of class Bay but we are trying to cast it to Ocean here it
is referencing with Lake so there is no relationship so
// it will give
ClassCastException
((Bay)var5).method1();
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME