by BehindJava

Can we restrict visibility of derived method in Java and What is visibility control in java

Home » java » Can we restrict visibility of derived method in Java and What is visibility control in java

In this blog, we are going to learn about the visibility control and visibility restrictions of the derived method in Java which is an important question in a Java interview.

Firstly, Go through this blog i.e., Access specifiers in Java.

  • If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
  • If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
  • If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

Note that a private method cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass.

public class Dog {
	
	public void bark() {
		System.out.println("Barking");
	}
	public void sniff()
	{
		System.out.println("Sniffing");
	}
	public void catchFrisbee()
	{
		System.out.println("Catching Frisbee");
	}
}

sss