+91 81900 98289

Java Inheritance

extends makes one class a more specific version of another. class Mentor extends Person says a mentor is a person and can use the person fields and methods. Java allows only one superclass.

super calls the superclass constructor or a superclass method. The super constructor call must be the first line of your constructor when you write it. If you omit it, Java inserts super() and the superclass must have a no-argument constructor.

Example

super(name) stores the name in Person. Mentor does not declare name again. It inherits the field.

class Person { String name; Person(String name) { this.name = name; } } class Mentor extends Person { Mentor(String name) { super(name); } } public class Inherit { public static void main(String[] args) { Mentor m = new Mentor("Anitha"); System.out.println(m.name); } }
Put shared fields in the superclass only when every subclass truly has them. A field that only a mentor needs belongs on Mentor, not on Person.