简体   繁体   English

Java初学者:子类和超类-可以删除值吗?

[英]Java Beginner: Subclasses and Superclasses -Can you remove values?

I'm a Java beginner and I'm looking into subclasses and superclass's. 我是Java的初学者,正在研究子类和超类。

I know you can add values/attributes/behaviour that aren't in a superclass to a subclass to make it more 'task specific'. 我知道您可以将超类中没有的值/属性/行为添加到子类中,以使其更“特定于任务”。

But my question is, can I remove an attribute or behaviour value that belongs in a superclass from a subclass? 但是我的问题是,我可以从子类中删除属于超类的属性或行为值吗?

simple answer: 简单的答案:

No you can't AND you shouldn't! 不,你不能,你不应该!

It should always makes sense that a superclass has an attribute. 超类具有属性应该总是有意义的。

Take a look at this: Liskov Substitution Principle 看看这个: Liskov替代原理

extend implies inheritance. extend意味着继承。 You don't have a precise choice over what you can inherit and what you can't. 对于可以继承和不能继承的内容,您没有精确的选择。

If parent class has decided to expose some public variables etc, sub class cannot alter that. 如果父类决定公开一些公共变量等,则子类不能更改它。

If the parent class doesn't want to expose some fields those can be marked as private . 如果父类不想公开某些字段,则可以将它们标记为private

Also: A class should be open for extending it but closed for changing it. 另外:应该打开一个类以扩展它,但关闭它以更改它。

您可能想看看访问级别修饰符: http : //docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

You can't remove superclass's variables and methods from subclass, but you can hide fields and override methods in subclass: 您不能从子类中删除超类的变量和方法,但是可以在子类中隐藏字段并覆盖方法:

class Employee {
    String name = "Employee";
    public void work() {
        System.out.println("Do some work");
    }
}

class Programmer extends Employee {
    String name = "Programmer";
    public void work() {
        System.out.println("Write programs");
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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