+ 2

Java Inheritance Example

Why does the following code display "New A New B"? class A { public A() { System.out.println("New A"); } } class B extends A { public B() { System.out.println("New B"); } } class Program { public static void main(String[ ] args) { B obj = new B(); } } /*Outputs "New A" "New B" */

9th May 2017, 2:38 AM
Kaien Yang
Kaien Yang - avatar
3 Respostas
+ 8
The constructor of the super class is invoked when declaring an object of the subclass. This must happen so variables/fields that could be extended on can be initialized.
9th May 2017, 3:29 AM
Rrestoring faith
Rrestoring faith - avatar
+ 2
simply said because the base A (parent) class must be constructed at first after that can be created the inherited class B.From that reason it was printed new A as the firts.
9th May 2017, 6:50 AM
Highman
Highman - avatar
0
//be attentive to access modifiers class Standard { protected void draw() { System.out.println("Drawing"); } protected void write() { System.out.println("Writing"); } } //fix the class class Pro extends Standard{ protected void useEffects() { System.out.println("Using Effects"); } protected void changeResolution() { System.out.println("Changing Resolution"); } } public class Main { public static void main(String[] args) { Standard standard1 = new Standard(); Pro pro1 = new Pro(); //standard version standard1.draw(); standard1.write(); //Pro version pro1.draw(); standard1.write(); pro1.useEffects(); pro1.changeResolution(); } } /*concept of the program is to change all private class to protected because private class we can't inharit*/
27th Sep 2022, 3:42 PM
Parthasarathi Panda
Parthasarathi Panda - avatar