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?

有帮助吗?

解决方案 2

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.

其他提示

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

You might want to take a look at the access level modifiers: 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归因
不隶属于 StackOverflow
scroll top