145k views
5 votes
suppose class b is derived from class a, and class c is derived from class b. in other words, we have: public class a { ... } public class b extends a { ... } public class c extends b { ... } which of the following is legal?

User Ajay Reddy
by
8.4k points

1 Answer

4 votes

There are several possibilities for the completion of the sentence, "which of the following is legal" without additional information about what we are asking for. Below are some options with explanations:

Creating an instance of class c:

java

c obj = new c();

This is legal because class c is derived from class b, which is derived from class a, and all the classes are accessible (public). Therefore, we can create an instance of class c using the constructor of class c.

Accessing a protected member of class a from an instance of class c:

java

public class a {

protected int x;

}

public class b extends a {

protected int y;

}

public class c extends b {

public void foo() {

x = 1;

}

}

This is legal because class c is derived from class b, which is derived from class a. The protected members of class a (such as x in the example above) are accessible to class c because it is derived from class b, which is a subclass of class a.

Accessing a private member of class b from an instance of class c:

java

public class a {

}

public class b extends a {

private int x;

}

public class c extends b {

public void foo() {

// illegal: x is not accessible from class c

// x = 1;

}

}

This is illegal because class c cannot access the private member x of class b. Private members are only accessible within the class in which they are declared.

Overriding a final method of class b in class c:

csharp

public class a {

public void foo() {

System.out.println("a.foo");

}

}

public class b extends a {

public final void bar() {

System.out.println("b.bar");

}

}

public class c extends b {

public void foo() {

System.out.println("c.foo");

}

// illegal: cannot override final method bar in class b

// public void bar() {

// System.out.println("c.bar");

// }

}

This is illegal because class b has a final method bar that cannot be overridden in class c. Final methods are explicitly marked as not intended to be modified by subclasses, so attempting to override them is an error.

Casting an instance of class c to class a:

java

c obj = new c();

a obj2 = (a) obj;

This is legal because class c is derived from class b, which is derived from class a. Therefore, an instance of class c is also an instance of class b and an instance of class a. We can cast the object to any of these types and it will still be a valid object of the original class. However, if we cast the object to a class that is not in the inheritance hierarchy of class c, we will get a Class Cast Exception at runtime.