Java OCA OCP Practice Question 1919

Question

Consider the following classes in one file named A.java...

abstract class MyClass {
   protected int m1 (){ return 0;  }
}
class MyClass2 extends MyClass {
   int m1 (){ return 1;  }
}

Which of the following statements are correct...

Select 1 option

  • A. The code will not compile as you cannot have more than 1 class in 1 file.
  • B. The code will not compile because class MyClass2 does not override the method m1() correctly.
  • C. The code will not compile as MyClass is an abstract class.
  • D. The code will not compile as MyClass does not have any abstract method.
  • E. The code will compile fine.


Correct Option is:B

Note

The concept here is that an overriding method cannot make the overridden method more private.

The access hierarchy in increasing levels of accessibility is:

private->'no modifier'->protected->public 

public is accessible to all and private is accessible to none except itself.

Here, class MyClass2 has no modifier for m1() so it is trying to reduce the accessibility of protected to default.

'protected' means the method will be accessible to all the classes in the same package and all the subclasses even if the subclass is in a different package.

No modifier (which is the default level) means the method will be accessible only to all the classes in the same package.

not even to the subclass if the subclass is in a different package.




PreviousNext

Related