質問

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