I am new to java and trying to understand some concepts. Here is a piece of code I don't understand.
public static Comparator<Fruit> FruitNameComparator = new Comparator<Fruit>()
{
public int compare(Fruit fruit1, Fruit fruit2)
{
return fruit1.quantity - fruit2.quantity;
}
};
I know what this is doing, but can't understand why this is allowed. So my questions are:
From the java doc, Comparator[T] is an interface. How about Comparator[Fruit]? I will suppose that it is a class, because it has to override the compare function.
Why can FruitNameComparator be intialized with a non-parameter constuctor and a class definition within the {}? I didn't find such constructor declaration in javadoc of Comparator[T].
Any input will be appreciated.
This code is using a feature of Java called anonymous inner classes. You specify the interface or superclass to implement/extend, along with an anonymous class body. Your anonymous inner class implements Comparator<Fruit>.
It's an anonymous class, which is an in-line concrete implementation of a type (either a super class or an interface).
Implementations are provided for whatever abstract methods are declared by the type.
In the case of super classes, the constructor called can not be specified, so arguments must be provided if there's not a default/no- args constructor.
In the case of interfaces, no parameters may be specified in the constructor because interfaces can not declare constructors.
Btw, I would be inclined to name your field fruitQuantityComparstor, rather than fruitNameComparator, as it compares quantities, not names.
Related
Why can't constructors be final, static, or abstract in Java?
For instance, can you explain to me why this is not valid?
public class K {
abstract public K() {
// ...
}
}
When you set a method as final it means: "I don't want any class override it." But according to the Java Language Specification:
JLS 8.8 - "Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."
When you set a method as abstract it means: "This method doesn't have a body and it should be implemented in a child class." But the constructor is called implicitly when the new keyword is used so it can't lack a body.
When you set a method as static it means: "This method belongs to the class, not a particular object." But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
The question really is why you want constructor to be static or abstract or final.
Constructors aren't inherited so can't be overridden so whats the use
to have final constructor
Constructor is called automatically when an instance of the class is
created, it has access to instance fields of the class. What will be
the use of a static constructor.
Constructor can't be overridden so what will you do with an abstract
constructor.
A Java constructor is implicitly final, the static / non-static aspects of its semantics are implicit1, and it is meaningless for a Java constructor to be abstract.
This means that the final and static modifiers would be redundant, and the abstract keyword would have no meaning at all.
Naturally, the Java designers didn't see in any point in allowing redundant and/or meaningless access modifiers on constructors ... so these are not allowed by the Java grammar.
Aside: It is a shame that they didn't make the same design call for interface methods where the public and abstract modifiers are also redundant, but allowed anyway. Perhaps there is some (ancient) historical reason for this. But either way, it cannot be fixed without rendering (probably) millions of existing Java programs uncompilable.
1 - Actually, constructors have a mixture of static and non-static semantics. You can't "call" a constructor on an instance, and it they are not inherited, or overridable. This is similar to the way static methods work. On the other hand, the body of a constructor can refer to this, and call instance methods ... like an instance method. And then there is constructor chaining, which is unique to constructors. But the real point is that these semantics are fixed, and there is no point allowing a redundant and probably confusing static modifier.
public constructor: Objects can be created anywhere.
default constructor: Objects can be created only in the same package.
protected constructor: Objects can be created by classes outside the package only if it's a subclass.
private constructor: Object can only be created inside the class (e.g., when implementing a singleton).
The static, final and abstract keywords are not meaningful for a constructor because:
static members belong to a class, but the constructor is needed to create an object.
An abstract class is a partially implemented class, which contains abstract methods to be implemented in child class.
final restricts modification: variables become constant, methods can't be overridden, and classes can't be inherited.
Final: Because you can't overwrite/extend a constructor anyway. You can extend a class (to prevent that you make it final) or overwrite a method (to prevent that you make it final), but there is nothing like this for constructors.
Static: If you look at the execution a constructor is not static (it can access instance fields), if you look at the caller side it is (kind of) static (you call it without having an instance. Its hard to imagine a constructor being completely static or not static and without having a semantic separation between those two things it doesn't make sense to distinguish them with a modifier.
Abstract: Abstract makes only sense in the presence of overwriting/extension, so the same argument as for 'final' applies
No Constructors can NEVER be declared as final. Your compiler will always give an error of the type "modifier final not allowed"
Final, when applied to methods, means that the method cannot be overridden in a subclass.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
No Constructors can NEVER be declared final. YOur compiler will always give an error of the type "modifer final not allowed"
Check the JLS Section 8.8.3 (The JLS & API docs should be some of your primary sources of information).
JLS section 8 mentions this.
Constructors (§8.8) are similar to methods, but cannot be invoked
directly by a method call; they are used to initialize new class
instances. Like methods, they may be overloaded (§8.8.8).
But constructors per say are not regular methods. They can't be compared as such.
why constructor can not be static and final are well defined in above answers.
Abstract: "Abstract" means no implementation . and it can only be implemented via inheritance. So when we extends some class, all of parent class members are inherited in sub-class(child class) except "Constructor". So, lets suppose, you some how manage to declare constructor "Abstract", than how can you give its implementation in sub class, when constructor does not get inherit in child-class?
that's why constructor can't be
abstract .
lets see first
final public K(){
*above the modifier final is restrict 'cause if it final then some situation where in some other class or same class only we will override it so thats not gonna happen here proximately not final
eg:
we want public void(int i,String name){
//this code not allowed
let static,, static itz all about class level but we create the object based constructor by using 'new' keyword so,,,,,, thatsall
abstract itz worst about here not at 'cause not have any abstract method or any declared method
Unfortunately in PHP the compiler does not raise any issue for both abstract and final constructor.
<?php
abstract class AbstractClass
{
public abstract function __construct();
}
class NormalClass
{
public final function __construct() {
echo "Final constructor in a normal class!";
}
}
In PHP static constructor is not allowed and will raise fatal exception.
Here in AbstractClass obviously a constructor either can be declared as abstract plus not implemented or it can be declared as something among (final, public, private, protected) plus a function body.
Some other related facts on PHP:
In PHP having multiple constructor __construct() is not possible.
In PHP a constructor __construct() can be declared as abstract, final, public, private and protected!
This code was tested and stood true for in PHP versions from 5.6 up to 7.4!
I've been wondering why it's allowed to do a code implementation in an interface, when interfaces are suppossed to contain no code implementation:
public interface someInterface{
String someString = "example";
}
I can make a class implement this interface, without getting an error:
public class someClass implements someInterface
How come?
You are allowed to declare constants in interfaces, which is what you have done. You have not implemented code.
Variables declared in interfaces are implicitly declared public static final.
The JLS, Section 9.3, covers this:
Every field declaration in the body of an interface is implicitly
public, static, and final. It is permitted to redundantly specify any
or all of these modifiers for such fields.
According to java docs
Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
Here you are not defined any methods to implement.So you didn't get any error here.
There is no strict condition that an interface must have signatured methods.Remember there are Marker Interfaces too in java.
And secondly , You can declare variables inside interface.
And that variable someString assigned in a static context and shared across all the implemntations by that interface
Point is that the variables inside declared interface are implicitly static and final.You can use them.
I’m reading an article about inner class. I found an example that demonstrates anonymous inner class (mentioned below).
button1 = new JButton();
button2 = new JButton();
...
button1.addActionListener(
new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
}
);
According to the example it creates an inner class for responding to a button using ActionListener interface. As I know an interface does not have a constructor. But I’m wondering, how they call a constructor.
"new java.awt.event.ActionListener(){
}"
An interface does not have a constructor, but an anonymous class does: like all classes, it extends java.lang.Object implicitly, therefore it can call the Object's parameterless constructor.
Moreover, Object's constructor is the only constructor you could call, because anonymous classes cannot define custom constructors.
Of course in addition to extending java.lang.Object your anonymous class implements ActionListener - that's why you can pass it to the addActionListener method.
you are constructing a subclass.
Have a quick look at the Java Specification - specifically the Default Constructor Section. You get a constructor because when you instantiate an instance of an interface it would be an Object.
Quote from the spec:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared.
Anonymous inner class: An inner class with no name.
Now the only detail here we care about is, this new class should subType the interface and for that we provide the necessary method implementations.
The constructor for this class is a default one and performs the job well because there are no instance variables associated.
new java.awt.event.ActionListener(){ }
This statement creates an anonymous class object that implements ActionListener interface.
That is you are invoking anonymous class default constructor not the interface one.
According to java docs
The anonymous class expression consists of the following:
1.The new operator
2.The name of an interface to implement or a class to extend.
3.Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: In the case of implementing an interface, there is no constructor, so you use an empty pair of parentheses.
How are Anonymous (inner) classes used in Java?
http://www.programmerinterview.com/index.php/java-questions/java-anonymous-class-example/
You are not instantiating an interface. You are asking the compiler to create an anonymous class implementing that interface and immediately create an instance of this class.
The best way to demonstrate this is to go to the "class" directory. You will find files of the form className$1.class, className$2.class, etc. These files correspond to those anonymous classes. If you were instantiating the interface itself, there would be no need for these new class files (and the anonymous classes they contain, of course).
That is how Anonymous Classes are(syntax wise).
According to the docs
The anonymous class expression consists of the following:
The new operator
The name of an interface to implement or a class to extend.
Parentheses that contain the arguments to a constructor, just like a
normal class instance creation expression. Note: In the case of
implementing an interface, there is no constructor, so you use an
empty pair of parentheses.
A body, which is a class declaration body. More specifically, in the
body, method declarations are allowed but statements are not.
As you know, in a java interface, all methods have to be defined as abstract. But when I define a method as not typing abstract, the compiler says it is okay. I know that an abstract method must not have a body. Does a method somewhere in an interface necessarily have a name abstract or not? : What i mean is, what is the difference between:
public interface blabla {
public void aMethod();
//or
public abstract void aMethod();
}
No, marking an interface method as abstract has no meaning and is never required.
All interface methods are implicitly abstract (and public too btw).
From the JLS:
Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.
Every method declaration in the body of an interface is implicitly public.
For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.
Related question (+ answer with a historical reference to a statement saying that abstract was once required for interface methods):
Java abstract interface
See the sample example below
interface xyz
{
void methodA();
}
Save this to xyz.java
Now compile this using javac tool
and then use the command given belo
javap xyz
the output would be
Compiled from "xyz.java"
interface xyz {
public abstract void methodA();
}
That means when you compile an interface, compiler makes its signature to public and abstract by default.
So it is not necessary to use abstract keyword for any method of interface.
I don't know that they have to be defined as abstract. Probably because they don't. See Oracle's tutorial.
you don't need to specify abstract (default) because within an interface it does not make sense as all the method of the interface needs to be implemented
All methods in an interface are abstract by definition.
You can't create an object out of an interface (e.g., using Interface i = new Interface();) so there's no difference between marking a method as abstract or not.
Any class that implements the interface needs to decide whether to implement it or to let a subclass do it. So as far as the interface is concerned, all methods are abstract by default.
An abstract method provides no implementation. A class which has an abstract method is necessarily abstract, which means that you cannot create instances of this class. To create an instance of that class, you need to subclass and provide non-abstract overwrites for the abstract methods.
An interface never provides an implementation of its methods and it cannot be instantiated. Therefore every method of an interface is per definition abstract. You do not need to provide the keyword abstract when declaring a method in an interface. And by convention the keyword abstract is not used within an interface.
The methods of an interface don't have to be explicitly defined as abstract because they are implicitly abstract and public as defined in the Java Language Specification §9.4. A redundant declaration is perfectly legal though.
If you forgot to put abstract keyword before interface method, Java will implicitly put public abstract keyword before it. Because all interface methods must be abstract.
In the Eclipse CDT plugin, I found this unusual way of initializing a field of an abstract class.
The field ALL refers is a class of the class itself.
abstract public class IndexFilter {
public static final IndexFilter ALL = new IndexFilter() {};
....
}
What is the role of new IndexFilter() {}; ?
Can you explain this initialization?
IndexFilter() {}; creates an "anonymous subclass" of IndexFilter. Since the braces are empty, the subclass does not override anything in the base class. Since IndexFilter is abstract, it cannot be instantiated directly, hence why a subclass is required.
I think what you refer to as "unusual" is the fact that it's an anonymous inner (or to be more precise, nested) class.
new IndexFilter() {} creates a concrete subclass of IndexFilter and an instance of that subclass in one expression. Obviously this is only possible because IndexFilter hasn't got any abstract methods. If it had, you'd have to provide an implementation for them between the curly braces.
It means that the filter will pass all information. Normally, filter meant to filter some entries. ALL is the special case here. You can also think of NONE as special case which will filter out all information.
Example:
a.select(b, IndexFilter.ALL);
a.select(b, new IndexFilter() {
...
});
Other class that uses such pattern is Integer which has MAX_VALUE and MIN_VALUE.
Looks like it's meant to just be a single easily-accessible instance of IndexFilter which doesn't override anything.