0

I am new to Java.Can someone please explain me this code?

abstract class Person {

private String name;
private String gender;

public Person(String nm, String gen){
    this.name=nm;
    this.gender=gen;
}

//abstract method
public abstract void work();

@Override
public String toString(){
    return "Name="+this.name+"::Gender="+this.gender;
}

public void changeName(String newName) {
    this.name = newName;
}   
}

class Employee extends Person {

private int empId;

public Employee(String nm, String gen, int id) {
    super(nm, gen);
    this.empId=id;
}

@Override
public void work() {
    if(empId == 0){
        System.out.println("Not working");
    }else{
        System.out.println("Working as employee!!");
    }
}

public static void main(String args[]){
    //coding in terms of abstract classes
    Person student = new Employee("Dove","Female",0);
    Person employee = new Employee("Pankaj","Male",123);
    student.work();
    employee.work();
    //using method implemented in abstract class - inheritance
    employee.changeName("Pankaj Kumar");
    System.out.println(employee.toString());
}

}

Here, why we use super()? I know that super() is used to call the base class' constructor ! But I am not fully aware of this! How the name and gender values are assigned to the constructor 'Person()' using super() .Can anybody explain this for me?

Kishan Lal
  • 473
  • 1
  • 5
  • 13

1 Answers1

1

Super () is used to call parent class constructor ...as the class may contain any numbers of constructors and these constructors are classified by the arguments passed to super() method....and yes it brings all types of variables to this current class constructor to use . Hope u got it .