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.
Related
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.
I am trying to find out, if it is possible to create anonymous inner class as abstract. I thought, that it doesn't make sense because I am trying to create instance of the abstract class, but the message from compiler confused me:
Class 'Anonymous class derived from Test' must either be declared abstract or implement abstract method 'method()' in Test
Code:
abstract class Test{
abstract void method();
}
Test o = new Test(){};
If it is possible to declare anonymous class as abstract, please let me know how to do that.
I would be greatful for answer.
See JLS Sec 15.9.5 (emphasis mine):
15.9.5. Anonymous Class Declarations
An anonymous class declaration is automatically derived from a class instance creation expression by the Java compiler.
An anonymous class is never abstract (§8.1.1.1).
An anonymous class is always implicitly final (§8.1.1.2).
An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).
you can't and does not make sense to declare anonymous class as abstract class as anonymous are used as local class only once.
i think you are getting this error because of similar issue Class must either be declared abstract or implement abstract method error
As quoted by Andy Turner the answer to your question is NO.
However I think you wanted to know something different.
Why do you get this compiler message?
Well the compiler is a bit misleading here. It offers two possible solutions based on that you are declaring a class (that anonymous class) and then also want to create an instance of that class:
make the derived class (which an anonymous class always is) abstract,
this is fine for normal and inner classes but it is not possible for anonymous classes, so the compiler should not suggest it in the first place
implement all methods and have no abstract methods in your anonymous class declaration
So to solve your actual problem: simply implement method() so your anonymous class declaration contains no more abstract methods
abstract class Test{
abstract void method();
}
Test o = new Test()
{
void method()
{
// do something
};
};
Now everything is declared and the compiler should not complain any more.
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 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?
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.