سؤال

well, I am currently developing an application which uses JFrame and Applet.

Why we can't extend both..

public class myClass extends Applet, javax.swing.JFrame {...}
//invalid...

The valid code is.

public class myClass extends Applet {
    javax.swing.JFrame frame = new javax.swing.JFrame();
    public void init(){
        frame.setSize(300, 400);
        frame.setVisible(true);
    }
}

Why so? Why we can't extends more than one class

هل كانت مفيدة؟

المحلول

The designers of Java learned from the mistakes made in other languages such as C++ where the diamond problem was an issue caused by multiple inheritance so decided to make Java a single inheritance language to simplify development.

نصائح أخرى

This is how Java works. It just doesn't support multiply inheritance. There are many reasons why multiply inheritance may be dangerous. For example there can be a name conflict.

On the other hand you can implement as many interfaces as you want to.

When a class is abstract or extended, you are specifying the role that the class plays. This also helps to prevent looping inheritence.

An interface is merely a contract that you will have provided method functionality in your class. If you want to inherit from multiple sources that don't specify the role of the class, use an interface.

Just like what Jakub said, multiple inheritance is not supported in java so you will have to use interfaces instead. It's just the nature of the language. I do hope that's what you're asking.

Java does not allowed multiple inheritance nativelly but you can simulate the "multi-inheritance" like that see.

Or you can use Java8 which allow you to use specific interface in which you can implement ONE method.

Multiple inheritance is not supported in java, to get around this the concept of Interfaces is used. You can inherit from as many interfaces you like to achieve multiple inheritance.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top