Welcome to our deep dive into Java Wildcards! In this lesson, we'll explore the mysterious world of wildcard types (?) and the superclass (super) that can help you write more flexible and reusable code.
Let's start from the beginning.
Wildcards are special symbols used in Java to represent a type that we don't know yet. They can help us create more generic methods and classes that can work with various types.
The "?" symbol represents an unknown type. It can be used in three different ways:
Upper bounded wildcard (? extends SomeSuperClass): The unknown type must extend a specific superclass or implement a specific interface.
Lower bounded wildcard (? super SomeSuperClass): The unknown type must be a superclass of a specific class or a superinterface of a specific interface.
Unbounded wildcard (?): The unknown type can be any class or interface.
The super keyword in Java refers to the immediate parent class of the current class.
Now, let's see these concepts in action with some code examples. ✅
// Superclass
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
// Subclass
public class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
// Generic method using upper bounded wildcard
public void showAnimal(Animal animal) {
animal.eat();
}
// Calling the method with a Dog object
Dog myDog = new Dog();
showAnimal(myDog); // Output: Animal is eating
myDog.bark(); // Output: Dog is barkingIn this example, we created an Animal superclass and a Dog subclass. We also have a generic method, showAnimal, that accepts an Animal or any of its subclasses. By using an upper bounded wildcard (Animal extends Animal), we ensure that the method can work with any Animal or any of its subclasses.
// Superclass
public class Vehicle {
public void drive() {
System.out.println("Vehicle is driving");
}
}
// Subclass
public class Car extends Vehicle {
public void honk() {
System.out.println("Car is honking");
}
}
// Generic method using lower bounded wildcard
public void showVehicle(Vehicle vehicle) {
vehicle.drive();
}
// Calling the method with a Car object
Car myCar = new Car();
showVehicle(myCar); // Output: Vehicle is driving
myCar.honk(); // Output: Car is honkingIn this example, we created a Vehicle superclass and a Car subclass. We also have a generic method, showVehicle, that accepts a Vehicle or any of its superclasses. By using a lower bounded wildcard (Vehicle super Vehicle), we ensure that the method can work with any Vehicle or any of its superclasses.
What does the "?" symbol represent in Java?
Now that you understand wildcards and the super keyword in Java, you can create more flexible and reusable code. By using wildcards, you can make your methods and classes work with various types without knowing their specific types at compile time.
Happy coding, and remember to keep learning and exploring! 💻🚀