Why I need Construct of subclass...Even there's no use of it... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why I need Construct of subclass...Even there's no use of it...

import java.util.Scanner; class Rectangle { double a,b; Rectangle(double a, double b) { this.a = a; this.b = b; } double areaS() { double areaS = a*b; return areaS; } } public class Volume extends Rectangle { Volume(double a, double b) { super(a, b); // TODO Auto-generated constructor stub } public static void main(String [] args) { double c,d; try(Scanner input = new Scanner(System.in)) { System.out.println("Enter the length: "); c = input.nextDouble(); System.out.println("Enter the width: "); d = input.nextDouble(); } Rectangle area = new Rectangle(c,d); System.out.print("Area on a rectangle : "+area.areaS()); } } https://code.sololearn.com/cRA792WEkI6m/?ref=app

23rd Mar 2020, 10:24 AM
I Am a Baked Potato
I Am a Baked Potato - avatar
6 Answers
+ 2
Tushar You can try running this but this requires 3 inputs. I have made few corrections and made it more readable. https://code.sololearn.com/ctG7BNuCHAMa/?ref=app
23rd Mar 2020, 11:15 AM
Avinesh
Avinesh - avatar
+ 1
You don't even need to extend the rectangle class and there is no need for subclass constructor because you are creating an object of Rectangle and not Volume. This is a little modified code of yours. https://code.sololearn.com/c83qtW2a1Cqe/?ref=app
23rd Mar 2020, 10:42 AM
Avinesh
Avinesh - avatar
+ 1
https://stackoverflow.com/questions/7173019/why-is-constructor-of-super-class-invoked-when-we-declare-the-object-of-sub-clas
23rd Mar 2020, 11:56 AM
Avinesh
Avinesh - avatar
+ 1
Avinesh Thanks!
23rd Mar 2020, 2:09 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
0
Avinesh Avinesh Brother actually I am practicing on inheritance related program so..I wanted to have parent class with length and breadth..for calculating area and then extend that class for calculating volume...just by adding height. Edit: I was coding in eclipse IDE and it showing error showing "Implicit super constructor Rectangle () is undefined for default constructor. Must define an explicit constructor." until I add that subclass constructor.
23rd Mar 2020, 10:54 AM
I Am a Baked Potato
I Am a Baked Potato - avatar
0
Avinesh Hey Thanks mate...But STILL I WANT TO KNOW...In my program why Constructor of subclass is needed...and If I remove it....it give me error. Thank you^^
23rd Mar 2020, 11:52 AM
I Am a Baked Potato
I Am a Baked Potato - avatar