Search code examples
javaobjectoopinheritance

How Inheritance is used to set values?


In below code , Level class have a construtor where it uses super.

When happens when object is created with the value ?

I'm literally confused, even can't explain what's my doubt please explain the code.

Thanks in advance.

 public class Main
{
    public static void main(String[] args) {
      
     Base b = new Base(5);
     Base b1 = new Level(8);
      System.out.println(b.getV());
     System.out.println(b1.getV());
        
    }
}


class Base{
    private int value ;
    
    
    public Base(int value){
        this.value = value;
    }
    
    public void raisevalue(int v){
        this.value = value+ v;
    }
    
    public int getV(){
        return value;
}
}

class Level extends Base{
    public Level(int value){
        super(value);
    }
}

Solution

  • When you construct Level(99) it will call the constructor of Base and pass 99. The super is literally a call to the constructor of the Base class.

    if the constructor for Level had more to do, it could do it after the constructor on Base is called.