简体   繁体   中英

Is it a bad practice to override same static method in child class which is already defined in parent class in Java?

In this piece of code I have declared a parent class Animal containing static method eat and a child class of Animal containing same method. I just want to know if if it is a good practice to do this.

class Animal{
    public static void eat() {
        System.out.println("Animal Eating");
    }
}

class Dog extends Animal{
    public static void eat() {
        System.out.println("Dog Eating");
    }
}
  1. No, it is not a bad practice. Well your example is a good practice instead

  2. A better idea is in the parent class we declare the method as abstract , since anyway the child class will have its own logic, and the code in the parent class is meaningless.

`

class Animal{
    abstract void eat();
}
class Dog extends Animal{
    public void eat() {
        System.out.println("Dog Eating");
    }
}

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM