Java provide keyword this and and super
- this keyword
- refer to current object reference
- use to un-hide instance variable from local variable
- this() use to invoke current constructor
- Super keyword
- refer to parent (super class) object reference
- use to call (invoke ) accessible data member and member method of super class.
- super() : use to invoke super class constructor
Example :
public class Person { private String fname; public String lname; public Person(String fname, String lname) { this.fname = fname; this.lname = lname; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } @Override public String toString() { return "fname=" + this.fname + ", lname=" + this.lname ; } }
public class Student extends Person { private double salary; public Student(String fname, String lname) { super(fname, lname);// call super class constructor System.out.println("this sub class Constructor "); } public Student(String fname, String lname, double salary) { super(fname, lname);// call super class constructor this.salary = salary; } @Override public String toString() { // super.toString() invoke super class method return super.toString()+"salary=" + this.salary ; } public void disPlay() { System.out.println("First name :"+this.getFname()+"Last name: "+ super.lname+"salary=" + salary); // or // invoke super class toString method System.out.println(super.toString()+ " salary= " + salary); // or // keyword this can be delete => toString() System.out.println(this.toString()); } }
public class Test { public static void main(String[] args) { Student st = new Student("Learning","Tonight",100); System.out.println(st.toString()); st.disPlay(); } }
Output:
fname=Learning, lname=Tonightsalary=100.0 First name :LearningLast name: Tonightsalary=100.0 fname=Learning, lname=Tonight salary= 100.0 fname=Learning, lname=Tonightsalary=100.0