Can one class extend two classes?
@LA_: A class can implement multiple interfaces but extends only one class, so you can implement your class with all your interfaces without merging all into one interface, if you want.
Once you have created AbstractBillingActivity and PreferenceActivity as interfaces, you don’t need to create another interface named BillingInterface. Instead use this code: public class Preferences implements AbstractBillingActivity,PreferenceActivity
13 Answers 13
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 ?
Interfaces don’t work because they are interfaces. they only support public methods. See the problem discussed here: stackoverflow.com/questions/5376970/protected-in-interfaces
To be honest, the question was vague enough when it was asked nearly 10 years ago that at the time it made sense to suggest using interfaces. But even today, I still don’t see why interfaces wouldn’t work, or, rather, why you would absolutely need protected methods here.
Java doesn’t support multiple inheritance. You can implement multiple interfaces, but not extend multiple classes.
how should I use that AbstractBillingActivity (github.com/robotmedia/AndroidBillingLibrary) with Preferences then?
I don’t know. At first glance it doesn’t make sens to want to extend both something called Preferences and BillingActivity — I don’t see any link between these two. Use composition if your preferences need to store an billing activity thing or vice-versa.
where can I read about composition? This is something new for me. Or, could you please post an example? Thank you.
Another solution is to create a private inner class that extends the second class. e.g a class that extends JMenuItem and AbstractAction :
public class MyClass extends JMenuItem < private class MyAction extends AbstractAction < // This class can access everything from its parent. >>
Java 1.8 (as well as Groovy and Scala) has a thing called «Interface Defender Methods», which are interfaces with pre-defined default method bodies. By implementing multiple interfaces that use defender methods, you could effectively, in a way, extend the behavior of two interface objects.
Also, in Groovy, using the @Delegate annotation, you can extend behavior of two or more classes (with caveats when those classes contain methods of the same name). This code proves it:
class Photo < int width int height >class Selection < @Delegate Photo photo String title String caption >def photo = new Photo(width: 640, height: 480) def selection = new Selection(title: "Groovy", caption: "Groovy", photo: photo) assert selection.title == "Groovy" assert selection.caption == "Groovy" assert selection.width == 640 assert selection.height == 480
Addendum: I retract this answer: I have since learned that «object composition» is probably what you want to use if you need behavior similar to multiple inheritance. Also, implementing multiple interfaces would not be like multiple inheritance: You cannot have a class that implements two interfaces where both the interfaces contain a default method with the same signature unless the class provides an implementation for that method itself; therefore we still effectively have single inheritance. Always learning.
No you cannot make a class extend to two classes.
A possible solution is to make it extend from another class, and make that class extend from another again.
Java does not support multiple inheritance. However, your problem may be solved using interfaces.
The easiest solution would be to create an interface for AbstractBillingActivity and PreferenceActivity and implement them both.
What you’re asking about is multiple inheritance, and it’s very problematic for a number of reasons. Multiple inheritance was specifically avoided in Java; the choice was made to support multiple interface implementation, instead, which is the appropriate workaround.
I have one question for you.. I think Multiple Inheritance exist in java. Let me explain it Class A Class B. Class A extend the Class B and Class A also extend the Object Class. so how we can say java not support the Multiple inheritance..
Familiar with multilevel hierarchy?
You can use subclass as superclass to your another class.
public class PreferenceActivity extends AbstractBillingActivity <>
public class Preferences extends PreferenceActivity <>
In this case, Preferences class inherits both PreferencesActivity and AbstractBillingActivity as well.
Java does not support multiple inheritance, that’s why you can’t extend a class from two different classes at the same time.
Rather, use a single class to extend from, and use interfaces to include additional functionality.
I can think of a workaround that can help if the classes you want to extend include only methods.
Write these classes as interfaces. In Java, you can implements any number of interfaces, and implement the methods as default methods in the interfaces.
If you are interested in using methods from multiple classes, the best way to approach to it is to use Composition instead of Inheritence
In Groovy, you can use trait instead of class. As they act similar to abstract classes (in the way that you can specify abstract methods, but you can still implement others), you can do something like:
trait EmployeeTrait < int getId() < return 1000 //Default value >abstract String getName() //Required > trait CustomerTrait < String getCompany() < return "Internal" // Default value >abstract String getAddress() > class InternalCustomer implements EmployeeTrait, CustomerTrait < String getName() < . >String getAddress() < . >> def internalCustomer = new InternalCustomer() println internalCustomer.id // 1000 println internalCustomer.company //Internal
Just to point out, its not exactly the same as extending two classes, but in some cases (like the above example), it can solve the situation. I strongly suggest to analyze your design before jumping into using traits, usually they are not required and you won’t be able to nicely implement inheritance (for example, you can’t use protected methods in traits). Follow the accepted answer’s recommendation if possible.
Extending from two classes
Also, I would like to know that is this approach is okay that I have made the menus in class which is ControlMenu and I am extending in rest of the activities.
13 Answers 13
You can only Extend a single class. And implement Interfaces from many sources.
Extending multiple classes is not available. The only solution I can think of is not inheriting either class but instead having an internal variable of each class and doing more of a proxy by redirecting the requests to your object to the object that you want them to go to.
public class CustomActivity extends Activity < private AnotherClass mClass; protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); mClass = new AnotherClass(this); >//Implement each method you want to use. public String getInfoFromOtherClass() < return mClass.getInfoFromOtherClass(); >>
this is the best solution I have come up with. You can get the functionality from both classes and Still only actually be of one class type.
The drawback is that you cannot fit into the Mold of the Internal class using a cast.
you were quicker 🙂 I’ll leave my answer as some abstract rambling to compare to your concrete example 😉
As everyone else has said. No, you can’t. However even though people have said many times over the years that you should use multiple interfaces they haven’t really gone into how. Hopefully this will help.
Say you have class Foo and class Bar that you both want to try extending into a class FooBar . Of course, as you said, you can’t do:
public class FooBar extends Foo, Bar
People have gone into the reasons for this to some extent already. Instead, write interfaces for both Foo and Bar covering all of their public methods. E.g.
public interface FooInterface < public void methodA(); public int methodB(); //. >public interface BarInterface < public int methodC(int i); //. >
And now make Foo and Bar implement the relative interfaces:
public class Foo implements FooInterface < /*. */ >public class Bar implements BarInterface < /*. */ >
Now, with class FooBar , you can implement both FooInterface and BarInterface while keeping a Foo and Bar object and just passing the methods straight through:
public class FooBar implements FooInterface, BarInterface < Foo myFoo; Bar myBar; // You can have the FooBar constructor require the arguments for both // the Foo and the Bar constructors public FooBar(int x, int y, int z)< myFoo = new Foo(x); myBar = new Bar(y, z); >// Or have the Foo and Bar objects passed right in public FooBar(Foo newFoo, Bar newBar) < myFoo = newFoo; myBar = newBar; >public void methodA() < myFoo.methodA(); >public int methodB() < return myFoo.methodB(); >public int methodC(int i) < return myBar.methodC(i); >//. >
The bonus for this method, is that the FooBar object fits the moulds of both FooInterface and BarInterface . That means this is perfectly fine:
FooInterface testFoo; testFoo = new FooBar(a, b, c); testFoo = new Foo(a); BarInterface testBar; testBar = new FooBar(a, b, c); testBar = new Bar(b, c);
Hope this clarifies how to use interfaces instead of multiple extensions. Even if I am a few years late.
Since a class in Java cannot extend multiple classes. How would I be able to get by this? [closed]
It’s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
I have two classes that need to extend one class. I am getting a compiler error since this cannot happen in Java. I know that you can implement as many interfaces you want to in Java but can only extend one other class. How can I fix this problem?
By «I have two classes that need to extend one class» I think you mean «I have one class that needs to extend two classes.»
Best if you describe exactly what you’re trying to model, instead of the more general «how can I extend from two classes».
Closed as not a real question, even though it has been viewed 12,109 times. SO needs to change its behavior RIGHT NOW!
4 Answers 4
Use a «has A» relationship instead of «is An».
Multiple inheritance is almost always abused. It’s not proper to extend classes just as an easy way to import their data and methods. If you extend a class, it should truly be an «is An» relationship.
For example, suppose you had classes,
class Bank extends Financial class Calculator
You might do this if you want to use the functions of the Calculator in Bank ,
class Bank extends Calculator, Financial
However, a Bank is most definitely NOT a Calculator . A Bank uses a Calculator , but it isn’t one itself. Of course, in java, you cannot do that anyway, but there are other languages where you can.
If you don’t buy any of that, and if you REALLY wanted the functions of Calculator to be part of Bank ‘s interface, you can do that through Java interfaces.
interface CalculatorIntf < int add(int a, int b); >class Calculator implements CalculatorInf < int add(int a, int b) < return a + b >; > class Bank extends Financial implements CalculatorIntf Calculator c = new Calculator(); @Override // Method from Calculator interface int add(int a, int b) < c.add(a, b); >>
A class can implement as many interfaces as it wants. Note that this is still technically a «has A» relationship
Can you extend two classes in Java?
Java is an Object Oriented Programming language that lets you extend a class to another class .
Extending a class is also known as the inheritance mechanism. The new class inherits the properties and behaviors of the existing class.
Inheritance is useful because you can reuse the existing class definition as the base of the new class.
In the code below, the Poodle class inherits the Dog class, so you can call the Dog class methods and access its properties from the Poodle instance:
However, Java doesn’t support multiple inheritances. This means you can’t extend two or more classes in a single class.
Extending multiple classes will cause Java to throw an error during compile time:
When you need to extend two or more classes in Java, you need to refactor the classes as interfaces.
This is because Java allows implementing multiple interfaces on a single class.
In the following code, the Dog and Animal classes are refactored as interfaces:
As you can see from the example above, The Dog and Animal interfaces can be implemented in the Poodle class.
This allows you to access the properties and methods of Dog and Animal interfaces from any Poodle class instance.
To conclude, the inheritance mechanism in Java is limited to inheriting one class, but multiple interfaces can be inherited (implemented) on a single class.
An interface is a reference type used to specify the properties and behaviors of a class .
You can’t create an instance of an interface . Instead, you need to implement the interface on a class and instantiate the implementing class .
When you need to extend two classes or more, using interfaces is the only way to go in Java.
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter