MainMenu

Home Core Java Overview Maven Tutorials

Wednesday, 6 February 2019

Can we override a private or static method in Java?

Can we override a private or static method in Java?



Hello Friends,
In this article , we will describe that in java we can not override private or static method :-

You cannot override a private or static method in Java. If you create a similar method with same return type and same method arguments in child class then it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method in sub class because it’s not accessible there. What you can do is create another private method with the same name in the child class. Let’s take a look at the example below to understand it better.

Example :-

class Parent
{
private static void test()
{
System.out.println("Static or class method from parent");
}
public void quality()
{
System.out.println("Non-static or instance method from parent");
}
class Child extends Parent
{
private static void test()
{
System.out.println("Static or class method from child");
}
public void quality()
{
System.out.println("Non-static or instance method from child");
}
public class myprogram
{
public static void main(String args[])
{
Parent obj= new Child();
obj.test();
obj.quality();
}
}