Can I rename an implemented method in Java? - java

I have a class which is implementing an interface, and one of the methods is called onClick. Is there a way to implement the onClick that the interface wants but name it something else? Something like (and I'm making this up):
public void AnyMethodNameIWant() implements Interface1.onClick
Three reasons I'm asking are:
It would be nice to look at an method signature and know that it's
coming from an interface
To avoid 'generic' names like onClick that an interface may require me to have
To distinguish between the same method names in many interfaces
Apologies if this is a fundamentally 'bad' question as I am new to Java.

No, you can't. Interfaces have to be implemented by a method of the same name in Java.
You can use the #Override annotation with interface implementations (as of Java 6) though, which helps to clarify that this is a method which can't just be renamed arbitrarily.
One option for your second issue might be to create an implementation class just for the purpose of forwarding on the call to a more specific method. You might want to do this as a nested or even anonymous class. I'm not sure I'd usually do this though.
EDIT: Having seen the third question - no, if you have two interfaces with the same method signature in Java, you can only provide one implementation :( Oh, and if you've got two interfaces with the same signature but different return types, it's even worse. You could always write a method of Interface1 getInterface1() which returns an instance of an anonymous inner class proxying the Interface1 methods onto the "main" class.

Nope.
The only thing you could do is add a shadow method that implements the interface and calls your method.
public class MyClass implements Interface1 {
public void AnyMethodNameIWant() { ...; }
public void onClick() { AnyMethodNameIWant(); }
}

Those two points
To avoid 'generic' names like onClick that an interface may require me to have
To distinguish between the same method names in many interfaces
are usually solved by using the Adapter Pattern.
interface IFoo {
void onClick();
void onChange();
}
class MyImpl {
void doSomething(){
// real code for onClick
}
void doSomethingElse(){
// real code for onChange
}
IFoo getFooAdapter(){
return new IFoo() {
#Override
public void onClick() {
doSomething();
}
#Override
public void onChange() {
doSomethingElse();
}
};
}
}
Basically you create an intermediate step which forwards all calls to any interface method to the real implementation.
Naming and signatures can vary. You can also offer different adapters for different interfaces if you want (or must if both interfaces have competing method with different behaviour).
There are quite some possibilities how to hand out the adapter instance - creating a new one every time might not be wise in certain circumstances.
Of course this pattern is nothing you implement just for fun or just for minimal and clean code. But it can solve real problems.

You can't rename the method, but you could define both methods (onClick and anyMethodNameIWant) and have onClick just simply call your other method.
#Override
public void onClick() {
anyOtherMethodNameIWant();
}

You of course can have additional methods with different names that point to the same implementation to get the naming you desire.
public void interfaceMethodA(){
// some implementation here
}
public void AnyMethodNameIWant(){
interfaceMethodA();
}

Related

How to declare a method that can be used only inside another method in a java interface?

How to declare a method that can be used only inside another method in a java interface?
public interface VendingMachine_ADT {
public void selectDrink(Drink d);
public void MoneyEntered(Coin c);
public void DrinkSelectedandMoneyEntered();
public void cancel();//i want this method inside selectDrink();
}
Although you can, with come coercion, achieve this in C++ (which somewhat legitimises this question), you cannot do this in Java.
All methods in a Java interface are necessarily public. Really the concept of a private method localised to a particular function is more to do with the implementation of that interface rather than the interface itself.
So you'd need to enforce your restriction in an implementation of selectDrink().
You cannot do that. All methods in an interface are meant to be public.
Apparently, you have several classes that implement VendingMachine_ADT, and they use a method named cancel that is the same for them - or at least similar.
In this case, you can make a base class for VendingMachine_ADT, and make cancel a protected method of the base class. Your cancel method will be available to descendant classes.
Depending on your needs, you could even have cancel as an abstract method, to be implemented by subclasses. That is as close to an interface as you can get.

How the compiler will get to know which print method should be called by obj.print();?

Here is an example of interface which is showing multiple inheritance.And i want to know how can we achieve multiple inheritance by interface and why can't we use it by class?
interface Printable // interface1
{
void print();
}
interface Showable //interface2
{
void print();
}
class TestTnterface1 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestTnterface1 obj = new TestTnterface1();
obj.print(); //which print method will be called now?
}
}
First question:
The implementation satisfies both contracts, so whether you cast your concrete class to Printable or Showable, it will be used just the same. You will notice that there is an "impossible" situation, like this:
public interface Printable{
String print();
}
public interface Showable{
void print();
}
public class Impl implements Printable,Showable{
/*impossible to implement because you cannot have the same method signature with two different return types*/
}
The multiple inheritance would usually imply there is something useful added by each parent. For example, if Printable would have the method #print and Showable would have the method #show, inheriting them both would add functionality to your program.
If you want to combine functionality from several concrete classes, you might want to look into composition instead of inheritance.
The answer to the second question is more tricky. You can find a longer discussion here. While it would have been possible for the creators of Java to put in such option, it would have opened the door to some pretty messed up code. Think of the example you gave: what if Printable and Showable had concrete implementations for the #print method? Which implementation should the inheriting class have chosen?
In any case the runtime will call the TestTnterface1#print() method, because it is the implementation (code that can be executed).
An interface is a contract that the class that implements must follow, and is used only at compile time. The compiler checks, if the implementor has (non abstract) methods with same name and signature.
There is only one concrete method that can be called
i.e.
class TestTnterface1 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
Question 1: Which method is called?
There is only one method-implementation that can actually be called. So, there is no ambiguity.
Question 2: How can we achieve multiple inheritance by interface?
You already gave an example for this. The special point about this kind of inheritance is that there can't be multiple implementations (until Java 7). Java 8 in contrast allows default methods in interfaces.
Question 3: Why can't we use it by class?
It avoids inheritance of state.
https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html gives some more information.
Since both interfaces have print() method and TestInterface1 class has its implementation, it will call its implementation.
public void print()
{
System.out.println("Hello");
}

Invoke a method on all subclasses from superclass?

I have recently stubled upon something that has always annoyed me.
Whenever I want a method to be invoked in all classes that have a certain interface, or if they are extensions, I would like to have a keyword that does the opposite of the keyword super. Basically, I want the invocation to be passed down (if a class inherits a method, and the method in the superclass is called, it will be called in the subclass as well). Is there anything that resembles what I am asking for?
EDIT:
The contemporary methods I am using are efficient, but not as efficient as I would like them to be. I am only wondering if there is a way of invoking a method, that has been inherited, from its superclass/superinterface. The last time I was looking for this, I did not find it either.
NOTE: All of the subclasses are unknown, hence impossible to utilize. The only known class is the superclass, which is why I can't invoke it. This can be solved using the Reflections API, which I am currently using. However, it does not always comply with what I am searching for.
Every method in Java is virtual with the exception of static methods, final methods and constructors meaning that if a subclass implements the method being invoked, the subclass's implementation will be called. If the subclass wishes to also invoke the immediate superclass method, that is accomplished via a call to super.
This is very common with abstract classes where some base class is utilized by a framework, but clients are expected to override. For instance:
public abstract class Drawer{
public void draw(){
//setup code, etc common to all subclass implementations
doDraw();
}
protected abstract void doDraw();
}
public class CircleDrawer extends Drawer{
protected void doDraw(){
//implementation of how to actually draw a circle
}
}
Now, when you have an instance of CircleDrawer and you call draw(), the superclass Drawer.draw() method will be invoked that is, in turn, able to call CicleDrawer.doDraw().
Edit Now, if CircleDrawer was this:
public class CircleDrawer extends Drawer{
public void draw(){
//do stuff
}
protected void doDraw(){
//implementation of how to actually draw a circle
}
}
Any invocation of Drawer.draw() on an instance of CircleDrawer will always invoke the CircleDrawer.draw() method.
If you mean something like this:
class A {
public void func1(){
//do stuff
subclass.func1();
}
}
class B extends A{
public void func1(){
//do more stuff
}
}
class C extends A{
}
What happens when I call new C().func1()? Remember, func1 is not abstract and therefore, you cannot require classes to define it.
A better solution is to do the following:
abstract class A {
public void func1(){
//do stuff
func2();
}
public abstract func2();
}
class B extends A{
public void func2(){
//do more stuff
}
}
Hence, you require your subclasses to define a function that you can call from the super class.
The is no such a thing. When calling an overriden method in Java, the child-most class's method will be always called. If you want to call parent methods as well, you need to use super.methodCall() in every class's method of your hirearchy.
Unfortunately, I don't believe the thing you are trying to do is as possible as you may think. It's not quite that easy to invoke your subclasses from the super class, because not all subclasses may behave in the same way so a generic keyword for that functionality would wreak havoc! Although, by the phrasing of "Basically, I want the invocation to be passed down." it sounds like what you want is normal inheritance.
Just define the most generic similarities that all subclasses have in common in the superclass, then simply start each subclass definition of the method with super()
I don't mean to point out the obvious, but OO was designed for that and not for what you are asking. I doubt you'll be unable to find a way to do what you want within the typical arsenal of OO concepts
I think you got confused describing what you need, I don't think this:
Whenever I want a method to be invoked in all classes that have a certain interface, or if they are extensions
Is the same as this:
I would like to have a keyword that does the opposite of the keyword super
From what I understand, in the first one, you are referring to calling a method for all instances of a base class and its subclasses. For the second one, calling a subclass' method is exactly calling that method on a subclass which has probably overriden it.
I'm not sure what you are trying to do, maybe you should clarify with an example. Most likely, yours is a design problem which is solved in a different way than the one you are proposing. However, a "solution" came to mind when reading your question.
I'm a little more experienced with C# and python than with Java (and not even that much), but I'm sure more experienced programmers won't hesitate to correct me if I said stupid things.
You should have some kind of collection of objects of type of the base class and call that method, on each object, which each subclass must have overriden.
Maybe using the observer pattern, which is commonly used to reproduce event triggering, you can make all instances of a base class and its subclasses execute a "callback" whenever you want.

Why does all the interface methods need to be implemented in a class implementing it in java

I know that it is the purpose of the interface and the class can be declared abstract to escape from it.
But is there any use for implementing all the methods that we declare in an interface? will that not increase the weight and complexity of the code if we keep on defining all the methods even it is not relevant for that class? why it is designed so?
The idea of an interface in Java is very much like a contract (and perhaps seen in retrospect this should have been the name of the concept)
The idea is that the class implementing the interface solemnly promises to provide all the things listed in the contract so that any use of a class implementing the interface is guaranteed to have that functionality available.
In my experience this facility is one of the things that makes it possible to build cathedrals in Java.
What you are critizing is exactly the goal interface achieve.
If you don't want to implement an interface, don't declare your class implementing it.
will that not increase the weight and complexity of the code if we
keep on defining all the methods even it is not relevant for that
class?
When you program against an interface, you want the concrete object behind it to implement all its methods. If your concrete object doesn't need or cannot implement all interface method you probably have a design issue to fix.
When any piece of code receives an instance of an interface without knowing what class is behind it, that piece of code should be assured of the ability to call any method in an interface. This is what makes an interface a contract between the callers and the providers of the functionality. The only way to achieve that is to require all non-abstract classes implementing the interface to provide implementations for all its functions.
There are two general ways to deal with the need to not implement some of the functionality:
Adding a tester method and an implementation that throws UnsupportedOperationException, and
Splitting your interface as needed into parts so that all method of a part could be implemented.
Here is an example of the first approach:
public interface WithOptionalMehtods {
void Optional1();
void Optional2();
boolean implementsOptional1();
boolean implementsOptional2();
}
public class Impl implements WithOptionalMehtods {
public void Optional1() {
System.out.println("Optional1");
}
public void Optional2() {
throw new UnsupportedOperationException();
}
public boolean implementsOptional1() {
return true;
}
public boolean implementsOptional2() {
return false;
}
}
Here is an example of the second approach:
public interface Part1 {
void Optional1();
}
public interface Part2 {
void Optional2();
}
public Impl implements Part1 {
public void Optional1() {
System.out.println("Optional1");
}
}
will that not increase the weight and complexity of the code if we
keep on defining all the methods even it is not relevant for that
class?
Yes you are right it will. That is why it is best practice in your coding to follow the Interface Segregation Principle which recommends not to force clients to implement interfaces that they don't use. So you should never have one "fat" interface with many methods but many small interfaces grouping methods, each group serving a specific behavior or sub-module.
This way clients of an interface implement only the needed methods without ever being forced into implementing methods they don't need.
It may depend on Liskov Substitution Principle
So, having A implements B means that you can use A when B is needed and, to make it work without problems, A must have at least the same methods of B.
Please keep in mind that mine is not a "proper" answer, as it's not based on official sources!
When implementing an Interface,we may not need to define all the method declared in the Interface.We can define the some methods,that we don't need,With nothing inside the body.

Confusion in regarding implementing interface methods

HI
I have a question If interface has got four methods,and I like to implement only two methods, how this could be achieved?
Can any explain is that possible or should I go for implementing all the methods.
You can't "partially" implement an interface without declaring the implementing class abstract, thereby requiring that some subclass provide the remaining implementation. The reason for this is that an interface is a contract, and implementing it declares "I provide the behavior specified by the interface". Some other code is going to use your class via the declared interface and will expect the methods to be there.
If you know the use case does not use the other two methods you can implement them by throwing OperationNotSupported. Whether this is valid or not very much depends on the interface and the user. If the interface can legitimately be partially implemented this way it would be a code smell that the interface is poorly designed and perhaps should have been two interfaces.
You may also be able "implement" the interface by doing nothing, though this is usually only proper for "listener" or "callback" implementations.
In short, it all depends.
If you control the design of the interface, simply split it in two. One interface specifies the two only some implementations implement, and one interface specifies the other two (or inherits the first two and adds more, your choice)
You can make the implementing class abstract and implement two of the 4 methods from the interface.
I think #sateesh 's answer is the one closer to solving your problem. Let me elaborate on it. First of all, it is imperative that any class implementing an interface should provide definitions for all of its methods. But in some cases the user may find no use for a majority of the methods in the interface save for one or two. Consider the following interface having 6 abstract methods:
public interface HugeInterface {
void a();
void b();
void c();
void d();
void e();
void f();
}
Suppose your code finds use for the method 'c()' only and you wish to provide implementation details for only the method 'c()'. You can create a new class HugeInterfaceAdapter in a separate file which implements all the methods of the interface HugeInterface like shown below:
public class HugeInterfaceAdapter implements HugeInterface {
public void a() {}
public void b() {}
public void c() {}
public void d() {}
public void e() {}
public void f() {}
}
Note that you need not provide any actual implementation code for any of the methods. Now comes the interesting part. Yes, your class in which the need to implement a huge interface arose in the first place.
public class MyClass {
HugeInterfaceAdapter mySmallInterface = new HugeInterfaceAdapter() {
#Override
public void c() {
//Your class-specific interface implementation code here.
}
};
}
Now you can use the reference variable mySmallInterface in all the places where a HugeInterface is expected. This may seem a little hackish but I may say that it is endorsed officially by Java and classes like MouseAdapter bears testimony to this fact.
It's not possible.
You can implement all four methods, but the two you don't need should throw an UnsupportedOperationException.
If you want a concrete class which is implementing this interface, then it is not possible to have unimplemented methods, but if you make have abstract class implementing this interface then you can leave any number of methods as you want to be unimplemented.
As other answers mention you cannot have a concrete class implementing only some of the methods of the interface it implements. If you have no control over the interface your class is extending, you can think of having Adapter classes.
The abstract Adapter class can provide dummy implementation for the methods of an interface and the client classes can
extend the Adapter class. (Of course the disadvantage is that you cannot extend more than one class)
This is common practice with GUI programming (using Swing) where the event listener class
might not be interested in implementing all methods specified by the EventListener interface. For example
take a look at the java.awt.event.MouseListener interface and and the corresponding adapter class java.awt.event.MouseAdapter.

Categories