Asked  6 Months ago    Answers:  5   Viewed   23 times

Is super() used to call the parent constructor? Please explain super().

 Answers

68

super() calls the parent constructor with no arguments.

It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists).

Also it can be used to call methods from the parent. I.e. super.aMethod()

More info and tutorial here

Tuesday, June 1, 2021
 
tpow
answered 6 Months ago
56

Every class that doesn't explicitly extend another class implicitly extends java.lang.Object. So super() simply calls the no-arg constructor of Object.

Note that this explicit call is unnecessary since the compiler would add it for you. You only need to add a super() call in a constructor when you want to invoke a superclass constructor with arguments.

Saturday, June 26, 2021
 
Kwadz
answered 6 Months ago
10

super() refers to the extended class (not an implemented interface). Which in this case is Object

So it will call the constructor in Object (Which does nothing)

Thursday, July 15, 2021
 
Nate
answered 5 Months ago
45

Check out java.text.AttributedString, which supports subscripts and more. e.g., in your paintComponent() you could go:

   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      AttributedString as = new AttributedString("I love you 104 gazillion");
      as.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 13, 14);
      as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 2, 6);
      g.drawString(as.getIterator(), 20, 20);
   }

Should look like this

Thursday, July 29, 2021
 
Palladium
answered 4 Months ago
86

You can't do this:

Cclass[] child = new Cclass[10];
Pclass[] parent = child;
parent[0]=new Pclass();

You should try doing this:

Cclass[] child = new Cclass[10];
Pclass[] parent = child;
parent[0]=new Cclass();

That's because, You first assigned the Pclass array to the child reference that can only have Cclass objects, then you are trying to assign Pclass object to the parent reference, that's not allowed!

See, what happens is that you have created a Cclass object on the heap when you wrote new Cclass, though the Cclass objects were null in the array but now they would accept only Cclass objects or it's subclass's objects

so assigning the Pclass object would be illegal!

Reason for getting a runtime exception and not compile time:

The compiler only checks whether the classes are in the same inheritance hierarchy or not, since they are in the same hierarchy you get a Runtime exception.

Monday, August 23, 2021
 
Gumbo
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share