java - could parent object be created using super to call parent method -


would parent object created , if use super keyword call method of parent class in child object?

outcomes show both mybase , mysub have same reference address. not sure whether demo.

class mybase {

public void address() {     system.out.println("super:" + this);     system.out.println( this.getclass().getname()); } 

}

class mysub extends mybase {

public void address() {     system.out.println("this:" + this);     system.out.println( this.getclass().getname()); }  public void info() {     system.out.println("this:" + this);     super.address(); } 

}

public class supertest {

public static void main(string[] args) {     new mysub().info(); } 

}

well, let's find out!

your test isn't quite going answer question. if want see if object created, why not create constructor prints console when called?

public class test {      static class parent {         parent() {             system.out.println("parent constructor called");         }          void method() {             system.out.println("parent method called");         }     }      static class child extends parent {         child() {             system.out.println("child constructor called");         }          @override         void method() {             system.out.println("child method called");             super.method();         }     }      public static void main(final string[] args) {         new child().method();     } } 

if run this, output:

parent constructor called child constructor called child method called parent method called 

so can see, when method() called, no parent object created when super keyword used. answer question "no".


the reason because super , super() different. super (no parentheses) used access members of parent class. super() (with parentheses) call parent constructor, , valid inside constructor first call in constructor. using super (no parentheses) not create new object.

also, super() doesn't create new, independent parent object. initialization work fields of parent needed before child constructor continues.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -