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 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

How to call a superclass method using Java reflection

If you are using JDK7, you can use MethodHandle to achieve this: public class Test extends Base { public static void main(String[] args) throws Throwable { MethodHandle h1 = MethodHandles.lookup().findSpecial(Base.class, “toString”, MethodType.methodType(String.class), Test.class); MethodHandle h2 = MethodHandles.lookup().findSpecial(Object.class, “toString”, MethodType.methodType(String.class), Test.class); System.out.println(h1.invoke(new Test())); // outputs Base System.out.println(h2.invoke(new Test())); // outputs Base } @Override public String toString() … Read more

super() raises “TypeError: must be type, not classobj” for new-style class

Alright, it’s the usual “super() cannot be used with an old-style class”. However, the important point is that the correct test for “is this a new-style instance (i.e. object)?” is >>> class OldStyle: pass >>> instance = OldStyle() >>> issubclass(instance.__class__, object) False and not (as in the question): >>> isinstance(instance, object) True For classes, the … Read more

Why call super() in a constructor?

There is an implicit call to super() with no arguments for all classes that have a parent – which is every user defined class in Java – so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent’s constructor takes parameters, and you wish to … Read more