Calling superclass from a subclass constructor in Java

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 … Read more

Why do I get “non-static variable this cannot be referenced from a static context”?

Your nested class (which isn’t a subclass, by the way) isn’t marked as being static, therefore it’s an inner class which requires an instance of the encoding class (JavaApp1) in order to construct it. Options: Make the nested class static Make it not an inner class (i.e. not within JavaApp1 at all) Create an instance … Read more

Why aren’t superclass __init__ methods automatically invoked?

The crucial distinction between Python’s __init__ and those other languages constructors is that __init__ is not a constructor: it’s an initializer (the actual constructor (if any, but, see later;-) is __new__ and works completely differently again). While constructing all superclasses (and, no doubt, doing so “before” you continue constructing downwards) is obviously part of saying … Read more

Inheritance in Java – creating an object of the subclass invokes also the constructor of the superclass. Why exactly?

It doesn’t create two objects, only one: B. When inheriting from another class, you must call super() in your constructor. If you don’t, the compiler will insert that call for you as you can plainly see. The superclass constructors are called because otherwise the object would be left in an uninitialized state, possibly unbeknownst to … Read more