Lambda does not override an interface method from a separate file - java

When the functional interface is in the same file where lambda overrides it, it compiles fine.
package test.test;
public class Base {
public static void main(String[] args) {
Interface1 a = n -> System.out.println(2*n);
}
}
interface Interface1 {
void multiplyByTwo(int x);
}
When the functional interface is in a separate file and Base class implements it, it fails to compile with Base is not abstract and does not override abstract method multiplyByFour(int) in Interface3 error.
package test.test;
public class Base implements Interface3 {
public static void main(String[] args) {
Interface3 b = n -> System.out.println(4*n);
}
}
package test.test;
public interface Interface3 {
void multiplyByFour(int x);
}
Is here something wrong? Why does lambda not override the method in the second case?

Your first example has:
public class Base {
which does not implement Interface1
However, your second example has:
public class Base implements Interface3 {
which DOES implement Interface3
Not sure what you are trying to do here, but this is intended behaviour:
Interfaces
When a class implements an interface, you must implement all of the methods into the class
For example:
public interface IFoo {
void bar();
}
and class:
public class FooImpl implements IFoo {
// must implement bar method in IFoo
public void bar() {
System.out.println("I did something");
}
}
Having a lambda in the main method does not constitute implementing interface methods.
Fix?
Just delete implements Interface3, you don't need to implement the interface in your class to be able to use it.

Related

How do I change the signature of a method I have overriden from my interface that I implemented onto the concrete class I'm using?

For example
//This is part of Comparable Interface:
public int compareTo(T other);//T being any class/type of parameter
//This is part of my own interface:
public void beeper(Object what);
//This is part of my own concrete class which implements both of the above interfaces
public int compareTo(Country other)//Java allows this...
{
//code stuffs....
}
public void beeper(String what)//This does not work...
{
//Code stuffs....
}
How would you make an abstract method that allows you to change the method signature like compareTo does?
Use parameterized type.
Parent interface :
public interface ParentClass<T>{
void beeper(T what);
}
Child class :
public class ChildClass implements ParentClass<String>{
public void beeper(String what){
// your impl
}
}
Comparable is using generics; you can, too:
public interface Beepable<T> {
void beeper(T what);
}
Your code would do this:
public class StringBeeper implements Beepable<String> {
public void beeper(String what) { // implement here }
}

What is the correct way to override method of interface from a child interface using generics?

I have those two interfaces:
public interface ApiResultCallback {
void onSuccess(RestApi.Success<?> successResult);
void onFailure(RestApi.Failure failureResult);
}
public interface GetHappyCowsCallback extends ApiResultCallback {
void onSuccess(RestApi.Success<List<HappyCow>> successResult);
}
Where Success and Failure are:
public static class Success<T> extends ApiResult {
public T data;
}
public static class Failure extends ApiResult {
public String message;
}
I get an error in GetCleverPointsCallback interface saying that
both methods have same erasure but neither overrides the other.
What does that mean? Shouldn't the method from GetHappyCowsCallback override the method of its parent?
What I'm trying to achieve here is some kind of mapping between callbacks and their data without having to implement long mapping functions or even worse, duplicating the Success class like this:
public static abstract class Success<T> extends ApiResult {
public T data;
}
public static class ListHappyCowSuccess extends Success<List<HappyCow>> {
}
void onSuccess(RestApi.Success<?> successResult);
And
void onSuccess(RestApi.Success<List<HappyCow>> successResult);
Do not have the same signature. So the second does not override the first
What you're trying to do can be achieved by making the interface generic:
public interface ApiResultCallback<T> {
void onSuccess(RestApi.Success<T> successResult);
void onFailure(RestApi.Failure failureResult);
}
public interface GetHappyCowsCallback extends ApiResultCallback<List<HappyCow>> {
}
In fact, you probably don't need the second interface at all. Such pseudo-typedefs are even considered an anti-pattern, because the new types cannot be exchanged with their equivalents.
If I have a method like this:
void myMethod(GetHappyCowsCallback callback);
I can not pass an ApiResultCallback<List<HappyCow>> to it.
In most cases interface overriding doesn't really make sense. Unless it involves default methods:
interface InterfaceA {
public void doSomething();
}
interface InterfaceB extends InterfaceA {
#Override
public default void doSomething() {...} // Provides a default implementation
}

Calling class's methods into an interface

I have created some interface such that:
public interface A{
}
and i would like to call the method a that I have already implemented in class B in interface A such that:
public class B{
public boolean a(){
return true;
}
}
public interface A{
public void call {
a();
}
}
without any errors, any help please?
What you want to do is strictly speaking impossible, as you cannot define method implementations in an interface. You can get something similar by defining an implementation of the interface that extends B. Hopefully that is close enough.
public class AImplementation extends B implements A{
public void call(){
a();
}
}
If you are using any java version before 8, then stick with the answers of #tinker and #Davis Broda. They provide better design since they do not couple your interface to the B class. If you insist however, in java 8 you can have default method implementations as well as static methods in an interface.
If your method is for inheritance then you have to use a default method. Add the default keyword:
default void call() {
...
}
Now the problem is how to get a reference to the class in order to call the method since you cannot have instance fields in interfaces. You have two choices:
Pass the object of B as a method parameter:
public interface A{
default void call(B b) {
b.a();
}
}
or make the method in B static
public interface A{
default void call() {
B.a();
}
}
If your method is not for inheritance but just a utility than you can make it static as :
public interface A{
public static void call() {
B.a();
}
}
I agree with #Davis Broda's answer, there is no way to have a method definition in an interface. But I have another way to address this.
You can have the interface and then have an abstract class implement this interface, and then have all other classes extend the abstract class. The abstract class doesn't have to extend the class from where you want to call the method, you could call it from an instance of that class too.
public interface A {
void caller();
}
public class B {
public void callMe() {
}
}
public class AbstractA implements A {
private B b;
public AbstractA(B b) {
this.b = b;
}
#Override
public void caller() {
b.callMe();
}
}
This way, all implementations of AbstractA will be able to call B's callMe method. And you can access this directly from the interface using this code:
A anInstance = someInstance;
anInstance.caller();
Your question is not very clear, but if I'm guessing right, you want interface A to be kind of a generic caller.
If you're using Java 8, you can achive that using a method reference:
public class B {
public boolean a() {
return true;
}
}
public interface A<T> {
default T call(Supplier<T> s) {
return s.get();
}
}
public class AImpl
implements A<Boolean> {
}
public class Sample {
public static void main(String[] args) {
AImpl a = new AImpl();
B b = new B();
boolean result = a.call(b::a);
System.out.println(result); // true
}
}
This uses Supplier<T> because your method a() in class B returns a boolean and does not receive any arguments.

calling non abstract method in abstract class java

I have 3 classes. It seems basic question. But I can'nt find answer by googling.
public abstract class Test {
void t1()
{
System.out.println("super");
}
}
public class concret extends Test{
void t1()
{
System.out.println("child");
}
void t2()
{
System.out.println("child2");
}
}
public class run {
public static void main(String[] args) {
Test t=new concret();
t.t1();
}
}
How do I call abstract class t1 method? Since I cant create object from abstract class how do I call t1 in abstract class?
Thank you.
Either you create a concrete class which doesn't override the method, or within a concrete class which does override the method, you can call super.t1(). For example:
void t1()
{
super.t1(); // First call the superclass implementation
System.out.println("child");
}
If you've only got an instance of an object which overrides a method, you cannot call the original method from "outside" the class, because that would break encapsulation... the purpose of overriding is to replace the behaviour of the original method.
you should be able to do it using
Test test = new Test(){};
test.t1();
Abstract class means the class has the abstract modifier before the class keyword. This means you can declare abstract methods, which are only implemented in the concrete classes.
For example :
public abstract class Test {
public abstract void foo();
}
public class Concrete extends Test {
public void foo() {
System.out.println("hey");
}
}
See following tests:
public abstract class BaseClass {
public void doStuff() {
System.out.println("Called BaseClass Do Stuff");
}
public abstract void doAbstractStuff();
}
public class ConcreteClassOne extends BaseClass{
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassOne Do Stuff");
}
}
public class ConcreteClassTwo extends BaseClass{
#Override
public void doStuff() {
System.out.println("Overriding BaseClass Do Stuff");
}
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassTwo Do Stuff");
}
}
public class ConcreteClassThree extends BaseClass{
#Override
public void doStuff() {
super.doStuff();
System.out.println("-Overriding BaseClass Do Stuff");
}
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassThree Do Stuff");
}
}
public class Test {
public static void main(String[] args) {
BaseClass a = new ConcreteClassOne();
a.doStuff(); //Called BaseClass Do Stuff
a.doAbstractStuff(); //Called ConcreteClassOne Do Stuff
BaseClass b = new ConcreteClassTwo();
b.doStuff(); //Overriding BaseClass Do Stuff
b.doAbstractStuff(); //Called ConcreteClassTwo Do Stuff
BaseClass c = new ConcreteClassThree();
c.doStuff(); //Called BaseClass Do Stuff
//-Overriding BaseClass Do Stuff
c.doAbstractStuff(); //Called ConcreteClassThree Do Stuff
}
}
use keyword 'super' to do that
void t1()
{ super.t1();
System.out.println("child");
}
Make sure you use that in the overriden method though.
Your code seems to call t1(). However this is calling the concrete t1() because the abstract t1() has been overridden by the concrete class.
If you wish to call the abstract t1 method from main code, do not override the t1() in concrete.
Or you can create a method in the concrete class for example:
public void invokeSuperT1(){
super.t1();
}
Create an anonymous Inner class,
Abstract class:
abstract class Test{
abstract void t();
public void t1(){
System.out.println("Test");
}
}
Here is how to create anonymous inner class:
Test test = new Test() {
#Override
void t() {
//you can throw exception here, if you want
}
};
Call the class via the object created for abstract class,
test.t1();
An abstract class is used when we want that every class that inherited from our abstract class should implement that abstract method, so it is must to implement method otherwise it gives the compile-time error.
void t1()
{
super.t1; // means the parent methods
System.out.println("child");
}
For example: Bird class has method sing() and there other classes that inherited from it like the sparrow, Pigeon, Duck, so these all have sing method so we make Bird class Abstract and make the sing() method abstract in it so every child of bird that implements Bird class should have a method of sing() with its on implementation.
First Create abstarct class like as shown in link: Creating Abstract Class
Create Sub-Classs like as shown in link: Sub-class extending
Creating main method for executing this as show in link: Instanciate the subclass to access
Result as shown here: Result

Any way to specify a java generic type variable that extends any one of multiple classes?

So suppose I have 2 classes:
public class A
{
public void
f()
{
}
}
public class B
{
public void
f()
{
}
}
I would like to write a generic static method that could call f when passed an instance of A or B. I tried:
public class C
{
public static <T extends A & B> void
g(T t)
{
t.f();
}
public static void main(String[] args)
{
A a = new A();
g(a);
}
}
But the compiler claims A is not a valid substitute for "T extends A & B", which I assume is because T must extend BOTH A and B, which obviously A does not. I could not find a way to specify something like "T extends A OR B". Is something like this not achievable? I am a java neophyte, so any help with this would be appreciated.
You can only specify one generic type. Use interfaces instead.
An interface specifies a certain set of methods, each member of it has to have. A class can implement multiple interfaces.
In your example, I would define an interface with the method f():
public interface MyInterface {
void f();
}
Let A and B implement the interface:
public class A implements MyInterface
{
#Override
public void f() {
// ...
}
}
public class B implements MyInterface
{
#Override
public void f() {
// ...
}
}
Then you can just specify the interface as type of the argument for your method:
public static void g(MyInterface obj)
{
obj.f();
}
For more detail on interfaces, check the Java documentation: What Is an Interface?

Categories

Resources