In Java and Android, method overriding is a feature that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Here is an example of how to override a method in Java and Android:
Java Example:
Suppose we have a superclass called Animal
with a method called makeSound()
. The Animal
class can be defined as follows:
public class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
Now, we can create a subclass called Cat
that extends Animal
. In this subclass, we can override the makeSound()
method to provide a specific implementation for the Cat
class:
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
Android Example:
Suppose we have an Android app that displays a list of items using a RecyclerView. We can create a subclass called MyAdapter
that extends the RecyclerView.Adapter
class. In this subclass, we can override the onBindViewHolder()
method to provide a specific implementation for our app:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
// ViewHolder class definition
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Bind the data to the ViewHolder
}
// Other methods of the MyAdapter class
}
In this example, the onBindViewHolder()
method is already defined in the RecyclerView.Adapter
class, but we override it in the MyAdapter
class to provide our specific implementation for binding the data to our ViewHolder
objects.