Interfaces in Java 8 [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
J. Bloch in his Effective Java written for Java 6 mentioned the following (Item 17):
If you feel that you must allow inheritance from such a class, one
reasonable approach is to ensure that the class never invokes any of
its overridable methods and to document this fact. In other words,
eliminate the class’s self-use of overridable methods entirely.
Item 18:
If you use abstract classes to define types, you leave the programmer
who wants to add functionality with no alternative but to use
inheritance. The resulting classes are less powerful and more fragile
than wrapper classes.
While interfaces are not permitted to contain method implementations,
using interfaces to define types does not prevent you from providing
implementation assistance to programmers.
Now in Java 8 with its default method's implementation (using the other methods in the interface) interfaces are dangerous for inheritance.
For instance:
public inteface MyInterface{
public void compute(Object o);
public default void computeAll(List<Object> oo){
for(Object o: oo)
compute(o); //self-use
}
}
So, according to J. Bloch, it may introduce some problems when we try to implement the interface, because:
Overriding the methods like this (similar to what J.Bloch provided):
public class MyInterfaceCounter implements MyInterface{
private int count = 0;
#Override
public void compute(Object o) {
count++;
}
#Override
public void computeAll(List<Object> oo){
count += oo.size(); //Damn!!
MyInterface.super.computeAll(oo);
}
}
The client access the interfaces's internals, i.e. they have to know about the default implementation.
What to do with it in Java 8? Are the rules from Effective Java apply still applicable?
Moreover, we can't declare the default method as final (as we can do for classes, it would make the self-use not too dangerous for overriders).

Okay, take the answer from your previous question and look what we can apply here:
You could simply avoid self-use.
In this case you can't. While implementing that interface your only choice to rely on (if you want to give a default implementation) is the method compute. You have to use it or not give an implementation at all.
You could make one of the methods involved final, so it can't be overridden.
That won't work in an interface as well.
You could make the class final, so it can't be extended.
That won't work in an interface.
You could describe the class's self-use patterns in its Javadoc comment (meeting the requirement of letting other people know).
That is the only choice left here. Either document it or don't give a default implementation.
So yes, the basic idea of it still applies, however your choices are somewhat limited.

Related

Why this code works if is suppose that an Inteface it is fully abstract? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Hello I'm new in java and I was testing the follow code in a java compiler but as my understanting an interface can´t have concrete methods but this one has concrete methods and works, can you explain me why ?? and output
"Sprinting!"
interface Run {
default void walk() {
System.out.print("Walking and running!");
}
}
interface Jog {
default void walk() {
System.out.print("Walking and jogging!");
}
}
public class Sprint implements Run, Jog {
public void walk() {
System.out.print("Sprinting!");
}
public static void main(String[] args) {
new Sprint().walk();
}
}
Unfortunately, there are a few low quality Java Tutorial sites (not naming names) that say that Java interfaces are "fully abstract"; i.e. that you can't include method code in an interface. And there are a lot of old articles and blogs that say the same thing. (And old textbooks too.)
This used to be true. Prior to 2014. It is not true anymore ... for any version of Java that is not past end-of-life.
In Java 8, the language was extended to support default methods. These are complete (i.e. not implicitly abstract) methods declared / defined in the interface itself. These default methods are inherited by all classes that implement the declaring interface, and can be overridden ... like methods inherited from a class.
The thing that sets a default method apart from a method in (say) an abstract class is that a default method cannot directly refer to any instance fields. The only way for a default methods to refer to the state of this is via other (non-default) method calls.
For more information about default methods, read the Oracle Java Tutorial:
The Java™ Tutorials: Default Methods
There is a lot more (correct / up to date) information on how inheritance works in Java in the surrounding pages.
In your example, you have two interfaces (Jog and Run) that both declare a default method with signature walk(). Your Sprint class implements both interfaces so both walk() methods are (notionally) inherited. That would be ambiguous ... if it weren't for the fact that Sprint also overrides the inherited walk() with its own declaration.
So ... when you call walk() on a Sprint object you get the override.

Java Virtual Field Pattern [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to understand and implement Java Virtual Field Pattern. So far I haven't been able to find many examples or resources on it. This particular resource explains it but not clearly on how it should be implemented. Would someone be able to better explain it or use a new example?
I'll try to explain the pattern using an example similar to the one from the linked mailing list in the linked resource.
Supposed there is a Peeker interface like this:
interface Peeker<T> {
T peek();
T take();
}
You want to your class to implement it but you don't want to implement all method yourself - you just want to delegate all method calls to an existing implementation of Peeker. So you might write your class like this:
class Foo implements Peeker<T>{
private Peeker<T> peeker = new PeekerImpl();
public T peek() {
return peeker.peek();
}
public T take() {
return peeker.take();
}
}
To avoid this boilerplate (especially if you have many other classes that use Peeker in a similar way) you can use the mentioned pattern. You extend the Peeker interface and use default methods to delegate all calls:
interface PeekerView<T> extends Peeker<T> {
Peeker<T> getPeeker();
default T peek() {
return getPeeker().peek();
}
default T take() {
return getPeeker().take();
}
}
Now the interface does all delegation automatically. Your class only has to implement the PeekerView interface and implement only the getPeeker method:
class Foo implements PeekerView<T>{
private Peeker<T> peeker = new PeekerImpl();
public Peeker<T> getPeeker() {
return peeker;
}
}
To implement the Pattern you basically just move all delegate calls to the PeekerView interface's default methods.
By the way I think "virtual field pattern", as Brian Goetz calls it, is not the best name for this. I guess it makes sense if you only look at the interfaces - the getter acts like a virtual field in this case. If you look at the whole thing though, including the implementing class, it is effectively like some kind of mixin (as it is also called in the other linked article). I would call it Mixin Pattern instead, because I've seen it referred to by that name more often.

Why isn't Number class in Java an interface rather than an Abstract class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I know that the byteValue() and shortValue() have implementations unlike the other abstract methods and were added in JDK1.1. This wouldn't have been possible if it was an Interface. But when the developers were writing Number class why did they make it an abstract class? Was it only because they expected that they might add more methods later on? I would only need answers supported by authoritative citations. thanks a lot everyone for the time you are taking to review my question and give answers.
Nobody here will know what went on in the minds of the designers, however abstract classes and interfaces are used for different purposes.
Classes (in Java) inherit in a strict hierarchy, and this hierarchy is a tool that can be used to ensure seperation of unrelated classes of objects. Classes are also more logical when the core functionality of the entire hierarchy is similar.
For example, with abstract classes Number and Letter it would not be possible to have a class that is both. With interfaces one could create a class that implements both which would make no sense.
Interfaces on the other hand are often used to expose a (usually) small piece of a class in a formal way so they can be used by reusable logic that uses only the functionality specified in the interface. They're more often used for adding supporting functionality, like Serializable, Comparable or Runnable.
An example, Printable and Comparable would be terrible abstract classes, as it would make it impossible to have a Comparable object also be Printable.
So the designers may have specifically chosen to make Number an abstract class to ensure that only one hierarchy of classes can be numbers, and nothing else. Perhaps it may allow for future optimizations where the JDK treats these classes as special cases, just like it does for String.

When not all your functions are polymorphic [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
From an old exam with no solutions:
Given this code....
import java.util.*;
public class AClass {
private int f(List<Integer> list){
int i = 0;
//Something useful
return i;
}
public int g() {
List<Integer> myList = new LinkedList<Integer>();
return f(myList);
}
}
Note that the method f is polymorphic, i.e. it can be passed any implementation of the interface List. On the other hand, the method g is not. As it constructs the object myList, it cannot do this without knowing its type. Consequently, it cannot be polymorphic. Our code contains many methods suffering from the same problem. We aim to make our code polymorphic.
What is the name of the standard solution to this problem?
Describe it in this case
Loose coupling There are many ways to solve that problem among them: program to interfaces and apply Dependency Injection
Method g() is tightly coupled to LinkedList because the method is explicitly instantiating that object hence tight to that class. If you want to for example use an ArrayList you need to open the class and explicitly modify the method and potentially introduce bugs. Additionally, you will probably need to retest and document. On the other hand method f() is way more flexible because you can just pass the collection you need and the method has no notion about the concrete implementation you are passing keeping in that way your method closed.
Consequently, it cannot be polymorphic. Our code contains many methods suffering from the same problem. We aim to make our code polymorphic.
What do you mean by that? Please provide an examples. The only way to make this code more generic is to use Collection or Iterable instead of List, but I'd say that's an overkill in terms of loose coupling.
Apparently, the solution in this case would be to create an Abstract Factory Pattern.
For example, we'd create a new class called AClassCreator and have a method createAClass(List<?> list) where the parameter is a subclass of list.

Appropriate methods to put into a util class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am working on a java class for parsing HTML and generating RDF (which I think I will eventually split into two classes - one for parsing and one for generating RDF).
At the moment I am creating a lot of methods for checking HTML data and converting it into a more uniform representation. Some of the methods I have created so far are:
public boolean isInteger(String str) { }
public boolean isTime(String str) { }
public boolean isDate(String str) { }
public String dateConverter(String[] date) { } //Converts a Norwegian date into mmddYYYY
Should I put methods like these into a util class? At the moment they are only being used by this specific class, but I think that they might need to be use them by more than this one class at a later point in time.
Well, yes, the methods you listed look like good candidates for public static methods in a util class. (The last 2 or 3 would fit nicely in a class called "DateUtils", for example.)
Of course, if you only use them in one place, they can just as well remain "private helpers" there, but as soon as you have multiple places using them, a util class makes sense.
(Edit: overuse of static methods can be problematic, but I think these methods could well be static utils because they are pure functions.)
They seem generic enough to be appropriate to put in a util class. I would, at the very least. Basically any class that parses String in your code would need to use those methods. I would make them static before adding them to the class though to avoid unnecessary construction.
Decomposition is a good habit to get into. If you are unsure about whether or not you need to use them, then go ahead and do so. It will give you practice with using utility classes.
It is a good practice to collect such methods in a utility class. Even if they are called from a single class at the moment, these kind of methods will be potentially reused by other clients in a near feature.
However, you must pay attention to make this utility class easy to be reused. To do this, the method signatures, actually their arguments, must be as generic as possible. They should not take inputs specific to a class.
Another advice of mine is dividing this utility class into more than one classes, if it begins to contain many incoherent methods. You can do this by grouping the relevant methods in a separate class. For example, methods you wrote can be moved to TypeUtils class and you can collect conversion related methods in Html2RdfUtils class for instance.
Finally, if you feel that these utility classes can be benefical to your other projects, you can collect them in a distinct library.
if you eventually want to split them into two classes, you may want to define the baseclass as interface or abstract class.
Base on your requirement, abstract class should be the right choose.
Put something in common from the child class to the abstract class.(You can implement method in the abstract class)
from another answer, I want to ask a question?
the answer suggest putting static in front of the method to avoid unnecessary construction, it very make sense.
I know the abstract class does not require to be instantiated to call its method.
it also can avoid construction.
There is the question?
Which way is more legit? or better? or just same.

Categories