1

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ojas Kale
  • 2,067
  • 2
  • 24
  • 39

6 Answers6

4

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 
     }  

 }
Sudhanshu Umalkar
  • 4,174
  • 1
  • 23
  • 33
3

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

You can do like this :

public class A extends javax.swing.JFrame{

...

}

and then

public class B extends A{

...

}
Abubakkar
  • 15,488
  • 8
  • 55
  • 83
1

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

Read this and this

Community
  • 1
  • 1
AmitG
  • 10,365
  • 5
  • 31
  • 52
1

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)
rai.skumar
  • 10,309
  • 6
  • 39
  • 55
1

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{
   ...
}
RE60K
  • 621
  • 1
  • 7
  • 26