In android, MainActivity
already extends Activity
.
Now I want to use an abstract class
say CountdownTimer
.
How can I do that because MainActivity
already extends one class and it cannot extend another.
In android, MainActivity
already extends Activity
.
Now I want to use an abstract class
say CountdownTimer
.
How can I do that because MainActivity
already extends one class and it cannot extend another.
You should use interfaces for this instead of abstract classes, since you can implement multiple interfaces or even implement multiple interfaces and extend a class.
The only caveat is that interfaces must have only abstract methods.
Short answer, you don't need to extend another class.
Android needs an Activity to display an interface. Your activity can "compose" a CountDownTimer
public class MainActivity extends AppCompatActivity {
private CountDownTimer timer;
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
timer = new CountDownTimer(...);
}
}
Multiple inheritance is not allowed in Java. So literally you can extend only one class. Consider changing your abstract class to an interface since you can implement multiple interfaces.
In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies
Scenario 1: As you have learned the following is not possible in Java:
public class Dog extends Animal, Canine{
}
Scenario 2: However the following is possible:
public class Canine extends Animal{
}
public class Dog extends Canine{
}
The difference in these two approaches is that in
The second approach there is a clearly defined parent or super class,
while in the first approach the super class is ambiguous.
Consider if both Animal and Canine had a method drink().
Under the first scenario which parent method would be called if we called Dog.drink()?
Under the second scenario, we know calling Dog.drink() would call the Canine classes drink method as long as Dog had not overridden it