Prerequisite : Overriding in Java, Packages in Java
Packages provide more layer of encapsulation for classes. Thus, visibility of a method in different packages is different from that in the same package.
How JVM find which method to call?
When we run a java program,
Java
Output:
2. Public method overriding : In this, access modifier of method we want to override is public.
Java
Output:
Java
Java
- JVM checks the runtime class of the object.
- JVM checks whether the object's runtime class has overridden the method of the declared class.
- If so, that's the method called. Otherwise, declared class's method is called.
// Filename: Hello.java
package a;
public class Hello {
private void printMessage()
{
System.out.println("Hello");
}
public void fun()
{
printMessage();
}
}
// Filename: World.java
package b;
import a.Hello;
public class World extends Hello {
private void printMessage()
{
System.out.println("World");
}
public static void main(String[] args)
{
Hello gfg = new World();
gfg.fun();
}
}
HelloAs private method of parent class is not visible in child class. Thus no overriding takes place here. If you don't know how to run this program from terminal then, create Hello.java file and World.java file as specified above and run these commands.
2. Public method overriding : In this, access modifier of method we want to override is public.
// Hello.java
package a;
public class Hello {
public void printMessage()
{
System.out.println("Hello");
}
}
// World.java
package b;
import a.Hello;
public class World extends Hello {
public void printMessage()
{
System.out.println("World");
}
public static void main(String[] args)
{
Hello gfg = new World();
gfg.printMessage();
}
}
WorldPublic method is accessible everywhere, hence when printMessage() is called, jvm can find the overridden method and thus call it. Thus overriding takes place here. 3. Default method overriding
// Hello.java
package a;
public class Hello {
void printMessage()
{
System.out.println("Hello");
}
}
// World.java
package b;
import a.Hello;
public class World extends Hello {
void printMessage()
{
System.out.println("World");
}
public static void main(String[] args)
{
Hello gfg = new World();
gfg.printMessage();
}
}
error: printMessage() is not public in Hello; cannot be accessed from outside packageVisibility of a default method is within its package only. Hence it can't be access outside the package. Thus, no overriding in this case. Predict the output of the following program
/* Hello.java */
package a;
public class Hello {
public void doIt()
{
printMessage();
}
void printMessage()
{
System.out.println("Hello");
}
}
/* World.java */
package b;
import a.Hello;
public class World {
private static class GFG extends Hello {
void printMessage()
{
System.out.println("World");
}
}
public static void main(String[] args)
{
GFG gfg = new GFG();
gfg.doIt();
}
}
Output:
HelloExplanation Visibility of printMessage() is default in package a. Thus, no overriding takes place here.