简体   繁体   中英

Without calling parents class constructor,it is possible to call direct child class constructor in java

I have a parents class whose name 'parents' and child class whose name 'child' which is extends parent class. if child class and parents class both having same argument but different behaviour constructor then if i am create child class objcet it will automatically call parents class constructor which i don't want.how it is possible.

Ex.

    class parents
    {
      parents()
      {
      
     System.out.println("hello, i am 
          parents class constructor");
      }
    }

    class child extends parents
    {
      child()
      {
     System.out.println("hello, i am 
  child class constructor");
      }
    }

    class main
    {
      public static void 
   main(String[] args)
      { 
        child c = new child();
      }
    }

Now here,

Output is.....

    hello, i am  parents class constructor
    hello, i am  child class constructor

But i want only...

    hello, i am child class constructor

Means only child class constructor is run not parent class.

How it is possible...

Whenever the constructor of a class is called, the constructors of its parent class are implicitly invoked as well.

The reasoning, as pointed in the comment by @SilvioMayolo, is that

"If you don't want the child to behave like the parent class, then it shouldn't be a parent class."

Conceptually, it is a child class is because the child inherits some properties or functionalities from its parent . As in your example, if you don't want "hello, i am parent class constructor" to be printed when the child constructor is called, you actually do not need the parent class of the child to actually be its parent.

Therefore, what functionality you want to achieve is not possible in Java because it is an implicit feature of the language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM