Welcome to a tutorial that will unravel the mysteries of the 'this' and 'super' keywords in Java. These two keywords play a crucial role in object-oriented programming, allowing you to navigate class hierarchies, manage variables, and write more maintainable code.
class Person {
String name;
Person(String name) {
this.name = name; // 'this' refers to the current object
}
void introduce() {
System.out.println("Hello, I am " + this.name);
}
}
Person person1 = new Person("Alice");
person1.introduce(); // Output: Hello, I am Alice
class Animal {
String species;
Animal(String species) {
this.species = species;
}
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
String breed;
Dog(String species, String breed) {
super(species); // Calls the parent class constructor
this.breed = breed;
}
void makeSound() {
System.out.println("Dog barks");
}
}
Dog myDog = new Dog("Canine", "Golden Retriever");
System.out.println("Species: " + myDog.species); // Output: Species: Canine
myDog.makeSound(); // Output: Dog barks
class Animal {
String name;
Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
String name; // Variable with the same name as the superclass
Dog(String species, String name) {
super(species);
this.name = name; // Use 'this' to refer to the subclass variable
}
void introduce() {
System.out.println("I am a " + super.name + " and my name is " + this.name);
}
}
Dog myDog = new Dog("Canine", "Buddy");
myDog.introduce(); // Output: I am a Canine and my name is Buddy
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
@Override
void start() {
super.start(); // Calls the start method of the parent class
System.out.println("Car started");
}
}
Car myCar = new Car();
myCar.start(); // Output: Vehicle started
// Car started
Summary: