Pergunta

Like what the title says, Can you make a public member of the superclass a protected member in a subclass? I had this question in my exam today, and I'm fairly new to programming. Can you explain how?

public class Animal {
int lifeExpectancy;
private int weight;
protected gender;
String name;
public String type;
 String genders;

public Animal(int le, int w, char g, String n){
    lifeExpectancy = le;
    gender = g;
    weight = w;
    name = n;
}

this is the subclass

public class Pet extends Animal{
private String home;
private Boolean biten;
String message;

public Pet(int le, int w, char g, String n, String h, Boolean b) {

    super(le, w, g, n);
    lifeExpectancy = le;
    gender = g;
    weight = w;
    name = n;
    home = h;
    biten = b;



}
Foi útil?

Solução

No. Lets say you have A extends B, remember that this means you can always use an A as a B.

 B b = new A();

So it can't be allowed for A to remove or restrict anything that B does, it can only extend it.

Outras dicas

Overriden method:

  • must not have a more restrictive access modifier
  • may have a less restrictive access modifier.

level of restriction (from the most restrictive):

  1. private
  2. defualt
  3. protected
  4. public

Declaring member variable (tutorial):

  • you will shadow variable

In Java Member is Constructor, Field or Method.

class X1 {
    public int x;
    public X1() {
    }
    public void x () {
    }
}

public class X extends X1 {
    protected int x;
    protected X() {
    }
    protected void x () {
    }
}

compiler finds only one error in above

- Cannot reduce the visibility of the inherited method from X1

and there is no way it might allow it. As for constructor and field we do not change visibility of super class members we are just declaring the new ones

You can just inherit the properties. That's it.

Consider a case that If you use a subclass in place of superclass and you modified the accessor of that subclass, that breaks OOP rules.

You can not reduce the accessibility of an inherited item. And only instance methods are inherited. So you can re-define an instance or static property (not a method) in a child class with lower accessibility.

For static methods you still can not drop the accesibility though they are not inherited.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top