Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one class extend two classes?

My class should extend two classes at the same time:

public class Preferences extends AbstractBillingActivity {  public class Preferences extends PreferenceActivity { 

How to do so?

Upd. Since this is not possible, how should I use that AbstractBillingActivity with Preferences then?

Upd2. If I go with interfaces, should I create:

  1. BillingInterface

    public interface BillingInterface extends PreferenceActivity, AbstractBillingActivity {  } 
  2. PreferenceActivity

    public interface PreferenceActivity {  } 
  3. AbstractBillingActivity

    public interface AbstractBillingActivity {          void onCreate(Bundle savedInstanceState);  } 

and then

public class Preferences implements BillingInterface { 
like image 870
LA_ Avatar asked Jul 05 '11 19:07

LA_


People also ask

Can a class extend 2 classes?

You can't extend two or more classes at one time. Multiple inheritance is not allowed in java.

Can classes extend each other?

A class can extend only one other class. To use the proper terminology, Java allows single inheritance of class implementation. Later in this chapter, we'll talk about interfaces, which take the place of multiple inheritance as it's primarily used in other languages. A subclass can be further subclassed.

Why we Cannot extend two classes in Java?

When one class extends more than one classes then this is called multiple inheritance. For example: Class C extends class A and B then this type of inheritance is known as multiple inheritance. Java doesn't allow multiple inheritance.

Can we extend multiple classes in Java?

Classes in Java support single inheritance; the ArmoredCar class can't extend multiple classes. Also, note that in the absence of an extends keyword, a class implicitly inherits class java.


1 Answers

Java does not support multiple inheritance.

There are a few workarounds I can think of:

The first is aggregation: make a class that takes those two activities as fields.

The second is to use interfaces.

The third is to rethink your design: does it make sense for a Preferences class to be both a PreferenceActivity and an AbstractBillingActivity?

like image 187
Etienne de Martel Avatar answered Oct 21 '22 02:10

Etienne de Martel