Abstract Class Creator Question

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

In the case of an abstract class, it is not created, so we know that the subclass creates and calls the constructor of the abstract class using the super method.

public class MainClass {
    public static void main(String[] args) {
        AbstractClassEx ex= new ClassEx(10,"Java");
        System.out.println();

        ClassEx ex2= new ClassEx();
        System.out.println();

        AbstractClassEx ex3= new ClassEx();
        System.out.println();

        ex.fun1();
        ex.fun2();
        System.out.println();
        ex2.fun1();
        ex2.fun2();
    }
}
public class ClassEx extends AbstractClassEx{
    public ClassEx() {
        // // TODO Auto-generated constructor stub
        System.out.println("ClassEx Constructor");
    }
    public ClassEx(int i,String s) {
        super(i,s);
        System.out.println("ClassEx constructor override");
        //System.out.println("i:"+i);
        //System.out.println("s:"+s);
    }
    @Override
    public void fun2() {
        // // TODO Auto-generated method stub
        System.out.println("fun2() start");
    }


}
public abstract class AbstractClassEx {
    int num;
    String str;
    public AbstractClassEx() {
        // // TODO Auto-generated constructor stub
        System.out.println("AbstractClass constructor");
    }
    public AbstractClassEx(int i, String s) {
        System.out.println("AbstractClass constructor override");
        this.num=i;
        this.str=s;
        System.out.println("i:"+i);
        System.out.println("num:"+this.num);
    }
    public void fun1() {
        System.out.println("fun1() start:"+num+" "+str);
    }
    public abstract void fun2();

}

However, when I created the objects of ex2 and ex3 in the main function, a constructor without a parameter value was called, and I wonder how it was called.

When creating a subclass in the original inheritance relationship, it is natural that the constructor is called because the parent class is created first, but the abstract class overlaps with the part that is not created and does not make sense

java abstract-class

2022-09-20 08:55

1 Answers

I understand that if you do not specify super() in the constructor of the child class in the inheritance relationship, the JVM will automatically add it.

Only if the parent class has a default constructor (a constructor without parameters).


2022-09-20 08:55

If you have any answers or tips


© 2022 pinfo. All rights reserved.