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.
Related
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 3 years ago.
Improve this question
Hello I'm a freshman in college. And just did a research about object oriented programming and the language that i'm studying is Kotlin, But i couldn't find a real reason why we need to use abstract class or methods at all.
For example :
abstract class Student(name: String, age: Int) {
init {
println("Student name is: $name")
println("Student age is: $age")
}
//non-abstract function
fun demo() {
println("Non-abstract function of abstract class")
}
//abstract function
abstract fun func(message: String)
}
class College(name: String, age: Int): Student(name, age) {
override fun func(message: String) {
println(message)
}
}
fun main(args: Array<String>) {
val obj = College("Chaitanya", 31)
obj.func("I'm a Blogger")
obj.demo()
}
reference : https://beginnersbook.com/2019/03/kotlin-abstract-class/
How is this showing only the essential data?
The purpose of abstraction is so you can ignore details that aren't relevant to you. When I'm working with a list of objects, I normally want to add, remove, and iterate. I don't want to worry about resizing an underlying array or adding and removing linked nodes. By using the abstract interface List, I can put those details inside a box and not have to think about them.
Abstract classes are only one kind of abstraction and are usually less important than interfaces. Their main usefulness is to allow you to collect common characteristics in one shared place to reduce duplication. For example, if I have a List, I always need a way to iterate over it, and there's no more efficient way to implement the contains method than to iterate over the list to look for the item. I can put this method in an abstract class, and then the actual implementations of the list (array, linked, something else) only have to provide a way to iterate.
Simply
Actually purpose of abstraction is selecting data from a larger pool to show only the relevant details to the object. It helps to reduce programming complexity and effort
Abstract class is that it allows you to group several related classes as siblings and it helps to reduce the complexity of the design and implementation process of software.
And abstract classes help to describe generic types of behaviors and object-oriented programming class hierarchy. Also it describes sub classes to offer implementation details of the abstract class.
Abstract methods are mostly declared where two or more sub classes are also doing the same thing in different ways through different implementations.Also it extends the same Abstract class and offers different implementations of the abstract methods.
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.
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 7 years ago.
Improve this question
Lets say I have an interface like
interface IMessage
{
void DoSomething();
void DoAnother();
}
Lets say in a big project 100 classes implemented this interface. But if I add a new method to IMessage interface like Foo();
interface IMessage
{
void DoSomething();
void DoAnother();
void Foo();
}
So my other 100 classes which implement this interface has to change. So does something wrong here? Changing all clasess? I hear about Open Close prensible so I used interface but in that situation, what is the logic?
Java 8 introduces "default" methods for interfaces; this means that you can provide a "default" implementation. This allows you to extend existing interfaces without adapting all implementing classes.
But if you are working older versions of Java - you nailed it: then you have to update all your classes.
And hopefully a final edit: modern IDEs are able to generate such "missing" methods for you; and depending on the complexity of what "Foo()" should do ... it might not be so much work in the end.
But there is one other option:
Instead of adding a new method to your existing interface, you could do
interface IMessageV2 extends IMessage {
void Foo();
}
This allows you to decide for each of your classes if you want to "update" the class to implement IMessage or IMessageV2. But of course, for those classes that you change to implement IMessageV2; you have to provide an implementation for any new method in that "new" interface.
The downside of this approach is that sooner or later, your client code will have to deal with objects that implement the V1, V2, V3, ... version of the interface. This can turn nasty, too.
Depends
Do you need this new void Foo() method in all the 100 classes.?
If Yes, then there is no other way and this is not wrong.
But if you want a similar interface but don't want those classes to have the change then write another interface
interface IMessageChild extends IMessage
{
void Foo();
}
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 8 years ago.
Improve this question
Consider that I have a class named Validation with five methods. All the methods are very complex and large. In a certain part of my application, I need to create a Validation object, but I'll only be using one method from that object. I could make the method static to fulfill my purpose, but for the rest of the application to keep working, those methods should be non-static.
So is there a way that I can create an object of a class containing only one of the non-static methods?
No.
About the best you can do (to answer the question as asked) is make the method protected and have a subclass of Validation which extends it. Then, if all the other methods are private, that object will only have the one protected one.
It's kind of a bad situation, though. More than likely, if you're trying to do this, you're either trying to optimize for no reason or you have a bad design somewhere.
e.g.,
public class Validation {
private void method1() {}
private void method2() {}
protected void method3() {}
private void method4() {}
}
...
public class RestrictedValidation extends Validation { }
...
public static void main(String[] args) {
RestrictedValidation validation = new RestrictedValidation();
validation.method1(); //compiler error
validation.method2(); //compiler error
validation.method3(); //success
validation.method4(); //compiler error
}
But yeah. I can't think of a single valid use-case for this.
You can solve this by way of inheritance where ValidationA would contain common methods used by most clients (here your one particular method), and a ValidationB class which extends ValidationA and add more specialized methods.
Or depending of the situation, it could be 2 completely different objects.
No there is no such way. An object consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.
what you is saying is create a person object(whose has already defined behaviour of walking and running) but he should only walk and not run. It does not make sense.
Jeff Gohlke provided a good solution to it
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.