How come not implementing some Methods are allowed in WindowAdapter? - java

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)

Related

What kind of declaration is this? [duplicate]

Can someone explain this Java syntax to me?
What are those brackets doing inside the outer parentheses?
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
It's called an anonymous inner class. It creates an unnamed class that extends WindowAdapter (it would also have been possible to specify an interface, in which case the class would implement that interface), and creates one instance of that class. Inside the brackets, you must implement all abstract methods or all interface methods, and you can override methods too.
This is an anonymous inner class -- the brackets denote the beginning and ending of the class declaration. This is a potentially useful SO question, and a bunch of others.
And to complement andersoj's answer, you usually use them when a method expects an instance of X, but X is an abstract class or an interface.
Here, you're actually creating a derived class from WindowAdapter, and overriding one of the methods to do a specific task.
This syntax is very common for event handlers / listeners.
It is an anonymous inner class. It is just a shortcut. You can imagine how the code would look like if you needed to create it as a top level class:
class CloseApplicationWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Then, inside your code you would do:
CloseApplicationWindowAdapter adapter = new CloseApplicationWindowAdapter();
addWindowListener(adapter);
Both solutions have exactly the same effect (althoug the anonymous class would create a Class$1.class file, for instance). Java programmers will often prefer the anonymous class approach if the anonymous class does not get too big/complicated/important.

How to create an Interface for a class that extends JDialog (or in general another class)

I'm developing a Java application that makes use of Swing.
I have a class that extends a JDialog, like this:
public class customDialog extends JDialog {
//Custom buttons listeners etc.
}
Now what is the manner (best practice) to create an interface for it?
I would write:
public interface customDialogInterface {
//Custom methods signatures
}
and then use the "implement customDialogInterface" in customDialog but in this manner when I use the customDialogInterface in my code I have no access to the JDialog methods.
Otherwhise JDialog is a class so I can't extend it in my interface. Furthermore I can't extend customDialogInterface with the interfaces that JDialog implements because one of them is package protected.
What is the correct manner to proceed in those (I suppose commons) cases?
UPDATE 1:
I'll try to explain better reformulating my question.
There is a programming principle that tells "program using interfaces and not concrete classes". Basing on it, how can I create an interface for my CustomDialog?
If I do:
public interface CustomDialogInterface {
public void doA();
public void doB();
}
than in the code that uses CustomDialog I have:
CustomDialogInterface myDialog = new CustomDialog();
myDialog.doA(); //OK
myDialog.doB(); //OK
myDialog.setVisible(true); //ERROR
UPDATE 2: I decided to update again my question because basing on the answer it seems that it is not very clear. It has not many info because it is not yet real code, it is just a theoretical question. Also if I yet found a possible solution I write here again in another form:
In my application I need a JDialog with my info, fields etc.
How can I obtain it?
Defining a class:
class MyImplementation extends JDialog {
public doA(String txt) {
//This is a method specific of my implementation
}
}
Now, I want to follow the rule of good programming "Program by interface, not by implementation" so I need an interface for my custom dialog
interface InterfaceForMyDialog {
public doA(String txt);
}
Obiously the class MyImplementation has to implement the interface so I change the pseudocode above just adding and implements
class MyImplementation extends JDialog implements InterfaceForMyDialog {
public doA(String txt) {
//This is a method specific of my implementation
}
}
Now finally I need to use my new dialog somewhere in the external code (let say somewhere in the main method) like this:
...
InterfaceForMyDialog myDialogInterface = new MyImplementation(...);
QUESTION:
How should you complete the code above to set some text to my custom dialog using the method "doA(String txt)" and then show the dialog itself ?
I think it is not possible using this structure and I found a solution (see below) using an abstract class. If I'm wrong or there is a better solution explain please write it here.
You are correct that you can only extend one class; since you are extending JDialog, you can implement 0 or more interfaces, but you cannot extend another class.
If your interface has two methods:
public interface customDialogInterface
{
public void doA();
public int doB();
}
then your class can have
public class customDialog extends JDialog implements customDialogInterface
as long as customDialog has the methods doA() and doB().
As a note: by convention, both class names and interface names start with capital letters. Java programmers the world over will find it easier to understand your code if you use CustomDialog and CustomDialogInterface.
Ok I found a solution.
Instead of declaring CustomDialogInterface as interface I declared it as an abstract class that extends the JDialog. Then I extend this abstract class with the class that provides the implementation.
If there is a better solution let me know!

Java initializing abstract classes

Can someone explain this line of code for me?
SomeAbstractClass variable = new SomeAbstractClass() { };
This properly instantiaties and stores the abstract instance in the variable. What is happening? An anonymous class that extends the abstract class, maybe? Any keywords I can use to look up information about this? (the abstract class also happens to be generic if that has any relevance)
The line above is creating an anonymous subclass of SomeAbstractClass, which will not be abstract. Of course, this will work only if the base class has no abstract methods to implement.
Actually, I cannot visualize an useful instance (besides "documentation" features, see the comment below) of the line above, unless you are implementing and/or overriding methods between curly braces. That is a quite common technique if the base class/interface happens to have few methods to implement and the implementation is simple. You can even refer to the final variables of the surrounding method and parameters, thus making a closure.
You are creating an anonymous class which is a subclass of your abstract class. Like was pointed out in comments, you are looking at an anonymous extends.
Something like follows would work if you had abstract methods to implement:
MyAbstractClass someObjectOfThatClass = new MyAbstractClass(){
#Override
public void someAbstractMethod(){
}
}
You can do the same with interfaces as they can also contain abstract methods. A practical example would be adding an ActionListener to a JButton:
myJButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
// code
}
});
Java gives you the ability to create anonymous subclasses inline. You often see this in the context of anonymous inner classes with Swing event handling, but there are many other applications as well.
In your example, you are creating a class that extends SomeAbstractClass anonymously and assigning it to a SomeAbstractClass reference. It would be just as if you created a separate class like this
public class SomeConcreteClass extends SomeAbstractClass {
}
and later did this
SomeAbstractClass variable = new SomeConcreteClass();
As noted by #Stefano, your approach only works if your anonymous concrete class has no abstract methods, which would be true because SomeAbstractClass has no abstract methods.

Anonymous class definition based on interface... maybe?

I saw this Java snippet in the book Spring in Action, but I'm not familiar with the language construct.
new RowMapper() {
public Object mapRow() throws SQLException, DataAccessException {
Motorist motorist = new Motorist();
motorist.setId(rs.getInt(1));
motorist.setEmail(rs.getString(2));
motorist.setPassword(rs.getString(3));
motorist.setFirstName(rs.getString(4));
motorist.setLastName(rs.getString(5));
return motorist;
}
}
According the Spring documentation, RowMapper is an interface. It looks to me like an anonymous class definition based on the RowMapper interface. The new keyword is a little confusing, making me wonder if this also creates one instance of the anonymous class. I would guess yes, because if the class has no name, how will you ever create an instance after the line that defines it?
Can anyone confirm my guesses that:
this is an anonymous class definition based on the RowMapper interface, and
it creates a single instance of that class?
This is an anonymous class definition based on the RowMapper interface
That's precisely what it is.
It creates a single instance of that class?
Yep. That's correct.
That code is implementing the interface in an anonymous way.
The syntax would be similar to:
Runnable runnable = new Runnable() {
public void run() {
}
};
Note the semicolon at the end of the declaration. Here the runnable object, though holds the reference to the Runnable interface actually contains the implemented object. That's runtime polymorphism for you!
Your guesses are entirely correct. An anonymous class definition may be based on either a non-final class or on an interface, and you must implement all abstract (or interface) methods. The only available syntax for declaring anonymous classes is new, which also has the effect of instantiating exactly one instance of the anonymous class (in the course of the program, though, many instances of the same anonymous class could be created, if this code is executed several times).
Interface tells what methods the built class instance should have or if thy are label interfaces, then what kind of behavior to associate with it.
Anonymous classes are classes that basically while instantiating a class instance thy are also extending it with custom code. So if you are instantiating a interface, then you must write all the methods described with that interface, and as long as you do at least that much, then compiler will be happy. This is what is done here.
IS this is an anonymous class definition based on the RowMapper interface?
Yes. As you can see mapRow() function has been written. And if you debug the code you can see, that is not a class of an instance of interface, but class that extends interface. In case of abstract class or just class, it would be same - extended. So if class is final you cant write anonymous class for it.
Does it create a single instance of that class?
Well, it extends it and makes an instance of it. It will be single instance and any sequent call to it would result in a different class. If you debug the code, then you can even see different class names dynamically associated with it.
Solely from the code above and without knowing about RowMapper, all you can assume is that a new anonymous class based on RowMapper (which may be an interface or a class) is instantiated.
Declaring Anonymous class and in below example it creates two instances .
public class Multithread {
void test(){
new Runnable() {
#Override
public void run() {
System.out.println("1");
}
}.run();
new Runnable() {
#Override
public void run() {
System.out.println("11");
}
}.run();}
public static void main(String[] args) {
new Multithread().test();
}
}

Can someone explain this Java syntax to me?

Can someone explain this Java syntax to me?
What are those brackets doing inside the outer parentheses?
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
It's called an anonymous inner class. It creates an unnamed class that extends WindowAdapter (it would also have been possible to specify an interface, in which case the class would implement that interface), and creates one instance of that class. Inside the brackets, you must implement all abstract methods or all interface methods, and you can override methods too.
This is an anonymous inner class -- the brackets denote the beginning and ending of the class declaration. This is a potentially useful SO question, and a bunch of others.
And to complement andersoj's answer, you usually use them when a method expects an instance of X, but X is an abstract class or an interface.
Here, you're actually creating a derived class from WindowAdapter, and overriding one of the methods to do a specific task.
This syntax is very common for event handlers / listeners.
It is an anonymous inner class. It is just a shortcut. You can imagine how the code would look like if you needed to create it as a top level class:
class CloseApplicationWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Then, inside your code you would do:
CloseApplicationWindowAdapter adapter = new CloseApplicationWindowAdapter();
addWindowListener(adapter);
Both solutions have exactly the same effect (althoug the anonymous class would create a Class$1.class file, for instance). Java programmers will often prefer the anonymous class approach if the anonymous class does not get too big/complicated/important.

Categories