Calling superclass from a subclass constructor in Java

蹲街弑〆低调 提交于 2019-11-27 01:59:31

What you should do:

Add a constructor to your super class:

public Superclass {
    public SuperClass(String flavour) {
       // super class constructor
       this.flavour = flavour;
    }
}

In the Crisps class:

public Crisps(String flavour, int quantity) {
    super(flavour); // send flavour to the super class constructor
    this.quantity = quantity;
}

 

Comments

Some comments to your question:

"In the superclass I have initialised the field with "

private String flavour;

This is not an initialization, it is a declaration. An initialization is when you set a value.

"I am getting an error " flavour has private access in the superclass" but I believe this shouldn't matter as I am calling the accessor method that returns it to the field?"

When you call a accessor (aka getter), it is ok - depends on the getter visibility. The problem in you code is the:

this.flavour = 

because flavour is not a field declared on Crisps class, but on the supper class, so you can't do a direct access like that. you should use my suggestion or declare a setter on the super class:

public void setFlavour(String flavour) {
    this.flavour = flavour;
}

Then you can use it on the child class:

public Crisps(String flavour, int quantity) {
    this.quantity = quantity;
    super.setFlavour(flavour);
}

flavour is private. Although you're reading it from the public method, you're assigning it to a private field, and you likely didn't declare it in this class.

You could set flavour to protected in the parent class or define a setter for it

Ultimately your code doesn't really make sense though. Even if it did compile, it would be more or less: flavour = flavour. Perhaps you should rethink what you're trying to do a little bit

I think you may need a tighter grasp on Java and Object Oriented Programming.

http://docs.oracle.com/javase/tutorial/java/concepts/

You should start here.

public crisps(String flavour, int quantity)
{
    super(flavour);
    this.quantity = quantity;
}

This should work as see Docs

make

    private String flavour;

public,otherwise your subclasses won't have access to this String. Your superclass doesn't know about existence of any subclass. According to Java documentation, "private" makes any variable and method available within that class,where private variable or method was declared, no any class has access to it,even subclasses. Once you chance your access modifier, you won't get any errors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!