Home > Net >  throw an error when extend one class to another
throw an error when extend one class to another

Time:01-30

i am trying to solve the problem but it throw an error. i make two classes one have constructor with two parameters and second have constructor wit no parameter when i extend first class to second it throw an error

   class c{

    public c(int a , int b) {
        System.out.println("c.<init>()");
    }
    
}
class f extends c{

    public f() {
    }
    
}

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

CodePudding user response:

Add default constructor to class c.

 public class c {

        public c(int a , int b) {
            System.out.println("c.<init>()");
        }
         public c() {
             
         }
    
}

CodePudding user response:

When you try to inherit from a class, it's subclass also adds superclass constructor before it's own constructor. When you try to make an object using constructor of subclass, the control flow in java will at first constructs a object of super class and parent class then will make object from sub class or child class. But in your code you added a constructor which needs two parameter,which program will not find at time of execution. So it will give error. You can declare a constructor for c without any parameter to solve this problem, through constructor over loading this problem can be easily solved, or you can remove the parameter of present constructor, so that it can be executed when subclass constructor calls it.

  class c{
    public c(int a , int b) {
    System.out.println("c.<init>()");
    }
    public c(){System.out.println("constructor without parameter");}
  }
  •  Tags:  
  • Related