Syntax
this.field = value;\nsuper.method();Examples
Using this to Resolve Naming Conflicts
Distinguishing a field from a same-named constructor parameter.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name; // this.name is the field, name is the parameter
this.age = age;
}
}Using this to Chain Constructors
Calling another constructor in the same class.
public class Box {
private int width, height;
public Box(int size) {
this(size, size); // calls the two-argument constructor below
}
public Box(int width, int height) {
this.width = width;
this.height = height;
}
}
Box square = new Box(5); // 5x5
Box rect = new Box(4, 8); // 4x8Using super to Call the Parent Constructor
A subclass constructor typically calls super() to initialize inherited fields.
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // must be the first line in the subclass constructor
this.breed = breed;
}
}
Dog dog = new Dog("Rex", "Labrador");Using super to Access an Overridden Method
Calling the parent's version of a method that the subclass has overridden.
class Vehicle {
public String describe() {
return "A vehicle";
}
}
class Car extends Vehicle {
@Override
public String describe() {
return super.describe() + " that is a car"; // extends, doesn't replace
}
}
Car car = new Car();
System.out.println(car.describe()); // A vehicle that is a carBest practices
- Use this. to disambiguate between a field and a parameter of the same name, a very common and idiomatic pattern in constructors
- A call to super(...) must be the very first statement in a subclass constructor - Java enforces this at compile time
- Use super.methodName() when a subclass override needs to extend the parent behavior rather than completely replace it
- You don't need this. for every field reference - use it specifically when there's a naming conflict or for clarity in constructors
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification