Ojas Kale
Ojas Kale

Reputation: 2159

Inheritance in Java: Extending another class when I've already extended one

I have to extend class A's variables into Class B. For that I have to write:

public class B extends class A

But in my case, the place is already taken up by "extends javax.swing.JFrame". It looks like:

public class B extends javax.swing.JFrame

Please suggest any method to inherit variables from class A to class B. I am very new to this field. So please explain.

Upvotes: 1

Views: 6537

Answers (6)

rai.skumar
rai.skumar

Reputation: 10667

Multiple Inheritance is NOT supported in Java. But still Java provides other ways to achieve multiple inheritance.

  1. Check if you can solve it by using interface, as you can implement multiple interfaces.
  2. Use composition or aggregation. Fundamentally, we achieve code re-usability using inheritance. The same can be achieved using composition/aggregation as well.
  3. Use Inner classes (you can extend multiple classes using inner classes)

Upvotes: 1

RE60K
RE60K

Reputation: 621

Make class A an interface and B implementing it like this :

public interface A{
public ....[Variables] 
}

public class B extends javax.swing.JFrame implements A{
   ...
}

Upvotes: 1

AmitG
AmitG

Reputation: 10543

Use composition or aggregation. Learn more about Has-A relationship.

Read this and this

Upvotes: 1

NPE
NPE

Reputation: 500167

Java does not support multiple inheritance, so you can't extend both A and JFrame.

You could either turn A into an interface, or embed an instance of A into B.

Upvotes: 3

Abubakkar
Abubakkar

Reputation: 15644

You can do like this :

public class A extends javax.swing.JFrame{

...

}

and then

public class B extends A{

...

}

Upvotes: 2

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

Either use composition or create an inner class in class B which extends class A.

 class B extends JFrame {
     A a = ... // this is one option

     class C extends A {
         // this is another option 
     }  

 }

Upvotes: 4

Related Questions