简体   繁体   中英

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

I'm a Java beginner and I'm looking into subclasses and superclass's.

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

extend implies inheritance. 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 .

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");
    }
} 

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