208k views
3 votes
Which statements are most accurate regarding the following classes?

class A {
private int i;
protected int j;
}

class B extends A {
private int k;
protected int m;

// some methods omitted
}

A) In the class B, an instance method can only access k, m.
B) In the class B, an instance method can only access i, j, k, m.
C) In the class B, an instance method can only access j, m.
D) In the class B, an instance method can only access j, k, m.

1 Answer

4 votes

Final answer:

The most accurate statement is D) In the class B, an instance method can only access j, k, m, because private members are not inherited, but protected members are, along with any members declared in the subclass itself.

Step-by-step explanation:

The correct statement regarding access to class members in inheritance is: D) In the class B, an instance method can only access j, k, m.
In Java, inheritance allows a subclass to inherit fields and methods from its superclass. In the given scenario, class B inherits from class A. The private field i from class A is not accessible within class B because private fields are only accessible within the class where they are declared. On the other hand, the protected field j is accessible within class B, as protected members can be accessed by the subclasses and classes within the same package. In class B, there are two additional fields, a private field k and a protected field m. Private fields and methods are accessible only within the class in which they are declared, while protected members are accessible within subclasses and classes in the same package. Therefore, an instance method in class B can access j, k, and m, but not i, which is why option D is the most accurate.

A) In the class B, an instance method can only access k, m.

B) In the class B, an instance method can only access i, j, k, m.

C) In the class B, an instance method can only access j, m.

D) In the class B, an instance method can only access j, k, m.

User Mybuddymichael
by
8.3k points

No related questions found