I ran into a difficulty while doing an assignment for school. The problem is that the assignment requires us to create a class SummableSet that inherits from class IntSet, but I also need SummableSet to extend Applet in order to create an Applet that the Assignment also requires. I'm not sure how to go about doing this since I've done my research and it is not possible for a sub-class to inherit two classes. So how can I create an applet from these two classes if I can not extend Applet in my sub-class, SummableSet?
As you know, your class can only extend from one other class, and the solution is not to try to do the impossible. You'll need to create at least two classes here, one that extends Applet (why your teacher is having you use a dead technology like applets is beyond me), and the other new class that extends IntSet. Then the Applet extending class would use the other class in a "has-a" or "composition" relationship.
e.g..,
public class MyApplet extends Applet {
private SummableSet summableSet = new SummableSet();
#Override
public void init() {
// use summableSet here
}
}
public class SummableSet extends IntSet {
// ...... code for SummableSet here
}
Related
The WindowAdapter class of Java is defined as an abstract class and has many abstract Methods, including:
windowClosing()
windowClosed()
windowActivated()
All of these methods are empty and Java says the class exists as a convenience for those who do not want to create classes implementing WindowListener. Because unlike the WindowListener Interface, WindowAdapter gives us the choice to implement only one of the abstract methods defined in it.
For example if I add the below code to a class that inherits from Window, I make the window closeable through the 'x' button on the upper right corner:
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
However this confuses me. First of all what exactly is happening here? Am I creating an inner class that extends WindowAdapter? The new keyword is normally used to create an instance, but obviously I am not allowed to instantiate an abstract class. So why the new keyword here?
Second, why do I get away with implementing only one of the abstract methods in WindowAdapter?
Normally in Java if I define an abstract class:
public abstract class UpperClassAb {
public abstract void test();
public abstract int boa();
}
and then try to use this class, just like I have used the WindowAdapterabove:
UpperClassAb tester = new UpperClassAb() {
public void test() {
System.out.println("mor");
}
};
I get an error, because I am not implementing all the abstract methods but only one of them. How can I get away with implementing just one of the abstract methods in the case of WindowAdapter? Is this a single case, and if not can I imitate this behavior?
Although WindowAdapter is an abstract class, its methods are not abstract but empty. So you do not have to implement them, but you can override them if you want.
https://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowAdapter.html
Regarding the new keyword: this is called an anonymous class. You basically create a new class without a name, and instantiate it at the same time. So the new class does not have a name, it extends WindowAdapter, overrides one method, and can ONLY be instantiated at this location (because it has no name)
If you are trying to implement WindowListener, you should provide implementation for all the methods. Here window adapter is nothing but the abstract class which provides partial implementations for the window events. Because of this you can provide the implementation for the particular event(e.g windowclose)
I am creating an incredibly primitive blackjack game for my high school programming class using Swing, therefore, all my resource classes extend JPanel. I created the following resource classes:
DealerBox
ClubsBox
SpadesBox
HeartsBox
My problem is that I want to create a handful of public integers such that I have
public int DealerTotal, ClubsTotal, SpadesTotal, HeartsTotal;
I want to do this so I can track the values of everybody's hands and determine winners and losers. I had a lightbulb go off and thought that making the Dealerbox a superclass to Clubs, Spades, and Hearts was the solution to all my troubles as I could have simple code in the superclass getting values for the above integers and do all the checking I need.
So I wrote this for one of my subclasses:
public class ClubsBox extends JPanel, DealerBox implements Runnable
{
//fun code
}
The problem now is that I keep getting an error. I assumed it had something to do with listing ClubsBox as being the subclass of JPanel AND DealerBox. So I stackoverflowed my problem and found an answer that stated that one cannot have a class that has 2 superclasses. Another answer to a similar question said that one COULD have a class that has two superclasses.
Now we get to the main question: Is it possible to have a class that has two superclasses? If so, how do I code it? If not, is there a way around the restriction?
EDIT: 21 APRIL 2014, 44 MINUTES AFTER ORIGINAL POST
I have a new problem. I used the method that everyone suggested which was to make DealerBox extend JPanel then to have everything else extend DealerBox. My GUI went from this:
To This:
The bottom one is clearly incredibly screwed up. Somehow labels from other areas ended up being copied and stuff got mixed around. If you need the code let me know, but I need serious help fixing this.
Please keep in mind the inheritance tree looks like this:
Unfortunately you can't have more than one direct superclass in Java. But you can chain them together like this:
public class DealerBox extends JPanel
public class ClubsBox extends DealerBox
Now with the new issue of your components not being laid out in the same manner as they were before, it's too hard to guess at what's going on without seeing some code. Are you putting common code into the constructor for DealerBox, and calling it from each DealerBox subclass? Like so:
public class DealerBox extends JPanel {
public DealerBox(String info) {
super(); // JPanel constructor
doSomething();
}
}
public class ClubsBox extends DealerBox {
public ClubsBox() {
super("Clubs"); // DealerBox constructor
}
}
Quote
"When Sun was designing Java, it omitted multiple inheritance - or more precisely multiple implementation inheritance - on purpose. Yet multiple inheritance can be useful, particularly when the potential ancestors of a class have orthogonal concerns. This article presents a utility class that not only allows multiple inheritance to be simulated, but also has other far-reaching applications.
Have you ever found yourself wanting to write something similar to:
public class Employee extends Person, Employment {
// detail omitted
}
Here, Person is a concrete class that represents a person, while Employment is another concrete class that represents the details of a person who is employed. If you could only put them together, you would have everything necessary to define and implement an Employee class. Except in Java - you can't. Inheriting implementation from more than one superclass - multiple implementation inheritance - is not a feature of the language. Java allows a class to have a single superclass and no more."
One option to you is "Inheritance from Inheritance":
public class Person extends Employee
public class Employee extends Employment
Multiple inheritance is not allowed in Java. So you cannot have two superclasses.
The way to get around this would have ClubsBox extend only DealerBox and then DealerBox itself extends JPanel.
ClubsBox:
public class ClubsBox extends DealerBox implements Runnable {
}
DealerBox:
public class DealerBox extends JPanel {
}
Classes in Java can only extend one class, your trying to extend two. They can; however, implement multiple interfaces.
You can have multiple inheritance though, something like this:
Class Integer extends Number ...
Class BigInteger extends Integer ...
Class ReallyBigInteger extends BigInteger ...
and so on and so forth, does this help?
No Java doesn't allow you to have more than one Super class or inherit more than one Parent class. This concept is called as multiple inheritance.The reason behind is the diamond problem to know more about multiple inheritance and Diamond problem check: https://www.geeksforgeeks.org/java-and-multiple-inheritance/
In Java, a child class cannot have more than one parent class. But what you want is be achievable, you can create a package, have classes in that package. And in the package where your current class is, you have to import that package. But remember, you have to keep the 'public' as access specifier.
I already read the post of research effort required to post a SO question. I am ashamed again to post this question to a pile of million questions. But I still don't get the idea of interfaces in java. They have unimplemented methods and then defined for every class in which they are implemented. I searched about it. Interfaces were used to support multiple inheritance in java and also to avoid (Deadly) Diamond Death of inheritance. I also came across Composition vs Inheritance and that inheritance is not for code reuse and its for polymorphism. So when I have a common code as a class to extend it will not be supported due to multiple inheritance which gives the option to use Interfaces(Correct me if I am wrong). I also came across that its not possible in most cases to define a generic implementation. So what is the problem in having a common definition (not a perfect generic implementation) of the interface method and then Override it wherever necessary and why doesn't java support it. Eg. When I have 100 classes that implements an interface 70 of them have a common implementation while others have different implementation. Why do I have to define the common method in interface over 70 classes and why can't I define them in Interface and then override them in other 30 classes which saves me from using same code in 70 classes. Is my understanding of interfaces wrong?
First, an interface in Java (as of Java 7) has no code. It's a mere definition, a contract a class must fulfill.
So what is the problem in having a common definition (not a perfect
generic implementation) of the interface method and then Override it
wherever necessary and why doesn't java support it
Yes you can do that in Java, just not with interfaces only. Let's suppose I want from this Example interface to have a default implementation for method1 but leave method2 unimplemented:
interface Example {
public void method1();
public String method2(final int parameter);
}
abstract class AbstractExampleImpl implements Example {
#Override
public void method1() {
// Implement
}
}
Now classes that want to use this method1 default implementation can just extend AbstractExampleImpl. This is more flexible than implementing code in the interface because if you do so, then all classes are bound to that implementation which you might not want. This is the advantage of interfaces: being able to reference a certain behavior (contract) without having to know how the class actually implements this, for example:
List<String> aList = MyListFactory.getNewList();
MyListFactory.getNewList() can return any object implementing List, our code manipulating aList doesn't care at all because it's based on the interface.
What if the class that uses interface already is a Sub-class. Then we
can't use Abstract class as multiple inheritance is not supported
I guess you mean this situation:
class AnotherClass extends AnotherBaseClass
and you want to extend AbstractExampleImpl as well. Yes, in this case, it's not possible to make AnotherClass extend AbstractExampleImpl, but you can write a wrapped inner-class that does this, for example:
class AnotherClass extends AnotherBaseClass implements Example {
private class InnerExampleImpl extends AbstractExampleImpl {
// Here you have AbstractExampleImpl's implementation of method1
}
}
Then you can just internally make all Example methods being actually implemented by InnerExampleImpl by calling its methods.
Is it necessary to have the interface in AnotherClass?
I guess you mean AnotherClass implements Example. Well, this is what you wanted: have AnotherClass implement Example with some default implementation as well as extend another class, or I understood you wrong. Since you cannot extend more than one class, you have to implement the interface so you can do
final Example anotherClass = new AnotherClass();
Otherwise this will not be possible.
Also for every class that implements an interface do I have to design
an inner class?
No, it doesn't have to be an inner class, that was just an example. If you want multiple other classes have this default Example implementation, you can just write a separate class and wrap it inside all the classes you want.
class DefaultExampleImpl implements Example {
// Implements the methods
}
class YourClass extends YetAnotherClass implements Example {
private Example example = new DefaultClassImpl();
#Override
public void method1() {
this.example.method1();
}
#Override
public String method2(final int parameter) {
return this.example.method2(parameter);
}
}
You can create an abstract class to implement that interface, and make your those classes inherit that abstract class, that should be what you want.
A non abstract class that implements and interface needs to implement all the methods from the interface. A abstract class doesn't have to implement all the methods but cannot initiated. If you create abstract class in your example that implements all the interface methods except one. The classes that extend from these abstract class just have to implement the one not already implemented method.
The Java interfaces could have been called contracts instead to better convey their intent. The declarer promise to provide some functionality, and the using code is guaranteed that the object provides that functionality.
This is a powerful concept and is decoupled from how that functionality is provided where Java is a bit limited and you are not the first to notice that. I have personally found that it is hard to provide "perfect" implementations which just need a subclass or two to be usable in a given situation. Swing uses adapters to provide empty implementations which can then be overrides as needed and that may be the technique you are looking for.
The idea of the interface is to create a series of methods that are abstract enough to be used by different classes that implement them. The concept is based on the DRY principle (Don't repeat yourself) the interface allows you to have methods like run() that are abstract enough to be usuable for a game loop, a players ability to run,
You should understand the funda of interface first. Which is
It is use to provide tight coupling means tight encapsulation
It helps us to hide our code from the external environment i.e. from other class
Interface should have only definition and data which is constant
It provide facility to class open for extension. Hence it cannot be replace by the any other class in java otherwise that class will become close for extension. which means class will not be able to extend any other class.
I think you are struggling with the concept of Object Oriented Design more than anything. In your example above where you state you have 100 classes and 70 of them have the same method implementation (which I would be stunned by). So given an interface like this:
public interface Printable
{
void print();
}
and two classes that have the "same" implementation of print
public class First implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
public class Second implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
you would instead want to do this:
public abstract class DefaultPrinter implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
now for First and Second
public class First extends DefaultPrinter
{
}
public class Second extends DefaultPrinter
{
}
Now both of these are still Printable . Now this is where it gets very important to understand how to properly design object hierarchies. If something IS NOT a DefaultPrinter YOU CANNOT AND SHOULD NOT make the new class extend DefaultPrinter
I have an Android app with an Activity, a Thread and a class to hold data.
I have created an abstract class ActivityTemplate which extends the Activity class and implements some callbacks, e.g. onTouchListener. This also includes some abstract methods.
I have created an abstract class (ThreadTemplate) which extends the Thread class and includes some abstract methods.
I have created an abstract DataTemplate class which holds some data elements and some simple methods to manipulate it.
I can produce my app by deriving three classes, one from each of the 'Template's above, but I really want to be able to roll them all up into a single MyTemplate class from which I can derive my app from.
Sort of:
public class MyTemplate extends ActivityTemplate, ThreadTemplate, DataTemplate
then
public class MyApp extends MyTemplate
But the MyTemplate class will not compile as you can only extend one class.
Any thoughts, or am I asking the impossible?
Use object composition instead of inheritance:
class MyApp {
private ActivityTemplate activityTemplate;
private ThreadTemplate threadtemplate;
private DataTemplate dataTemplate;
}
When using inheritance always ask yourself the question whether your subclass has an "is-a" relationship with the parent. In this case, MyApp is not a template. It has-a template.
Is there a easy way to extract a interface from a Java class such that it includes public methods of super classes.
The class Im trying to extract the interface has several layers of super classes, each one with lots of methods. I don't need an interface for each of those parent classes.
Currently I'm using InteliJ idea IDE. It only extracts public methods of current class, when extracting an interface. If U guys can tell me a tool or an easy way to extract interface, it would be a great help.
Eclipse doesn't offer superclass methods in the "Extract Interface" refactoring. And this is correct, because you really shouldnt implement an interface and implement the methods in a superclass!
You want something like this:
public interface InterfaceForB {
void b();
void a();
}
public class A {
public void a(){}
}
public class B extends A implements InterfaceForB{
public void b(){}
}
Yes, it compiles. But it's awful style, because it says, B implements the interface, which is just not true, because the a() method is implemented in class A.
My strong advice: use the refactorings as offered by IntelliJ, only extract methods to an interface that are really implemented by the actual class. Implement B for the given example so that it implements all interface methods:
public class B extends A implements InterfaceForB{
public void b(){}
public void a(){ super(); }
}
And now IntelliJ (and eclipse) can extract the interface the way you want it.
Eclipse has a tool called the "type hierarchy" which lets you view the members of only that class, the inheritance structure (including interfaces) of that class (as well as the members of that respective class/interface), and also any classes which extend/implement your class.
There are also refactory tools for extracting interfaces/super classes.