Java method that accepts references to interface objects - java

I'm kinda unsure about the following question:
If Launchable is a Java interface, what objects can be passed into the following method? What methods could be invoked on item inside this method?
public void prepareForLaunch (Launchable item) {
// some code
}
My current answer is:
From the above information, the only objects that can be passed into the method are objects that where instantiated as subclass types of the interface Launchable.(?) The methods that could be invoked on item inside the method would have to be public methods or protected methods within the same package. These methods would also have to be to be intended for a subclass of Launchable object since it is only in abstract and actual(concrete) classes where a method body’s definition can exist.
I was wondering if someone here can check my answer and add any suggestions. Thanks!

You can only pass in instances of classes that implement Launchable (either directly, or by inheritance from a superclass). You can also pass in null.
Inside of the method, you can call all the methods defined in Launchable (and in Object).
These methods would be defined in the Launchable interface, but implemented in the actual class (a fact that is guaranteed by the Java type system, which won't let you have classes with incomplete interface implementations, those would need to be declared abstract and cannot be instantiated).
If you need to call any other methods you need to know that the object in question also implements some other interface (or is of a given class), and do a typecast to that first.

Since you stated that Launchable is an interface, an instance of any class that implements Launchable could be passed to prepareForLaunch. Any class implementing Launchable would have to implement the methods defined in the interface and thus any method of Launchablecould be invoked to objects given to prepareForLaunch.

You are right about the first part. About the methods you can invoke: If you are not using casting then you can only invoke public\protected within the same package of Launchable. If you will use casting you can extend the range of the methods you can invoke to the methods in the casted-to class.
Consider this code:
public interface Launchable
{
public void aMethod();
}
public class SomeClass implements Launchable
{
public void aMethod()
{
}
public void bMethod(){}
}
Without casting youll be able to call
item.aMethod();
With Casting youll be able to call:
((SomeClass)item).bMethod();

you should use implements statement ,
public void prepareForLaunch() implements Launchbla {
}

Related

Why don't implement all method in interface Comparator?

Today, I'm trying to learn some features in Java 8, specific about Lambda Expressions. I create a new Comaparator like this :
Comparator<String> strCom = new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return 0;
}
};
When I read code inside Comparator interface, I have got confused. Althrough interface Comparator have two method compare() and equals(), we don't need implement all of them. I had found some reason why we don't need implement method equals() here. But i also read in javadocs
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. What Is an Interface?
So, can someone help me understand this ? Do not override equals() is still legal ?
equal is not needed to implement because it is inherited from the Object class, as everything in Java is an Object
As you can see in the documentation the equal Method is already defined in the Object class:
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
You only need to implement the equals method if you want to check if two Comparators have the same data and therefore are "equal", but this is probably not what are you looking for, as Comparators normally do not hold any instance variables
The tutorial is trying to introduce the concept of interfaces through a simple example, but it ends up being misleading.
Take this code for example:
public interface MyInterface {
public void foo();
public void bar();
}
public class Super {
public void foo() { System.out.println("foo"); }
}
public class Sub extends Super implements MyInterface {
public void bar() { System.out.println("bar"); }
}
This is perfectly valid code, despite the fact that Sub only explicitly implements one of MyInterfaces methods. It's easy to see why this is valid: foo() is already implemented by Super, and that implementation is inherited by Sub.
The exact rule goes like this:
Unless the class being declared is abstract, all the abstract member
methods of each direct superinterface must be implemented (§8.4.8.1)
either by a declaration in this class or by an existing method
declaration inherited from the direct superclass or a direct
superinterface, because a class that is not abstract is not permitted
to have abstract methods (§8.1.1.1).
While the rule only talks about direct superclasses, it is technically also true for indirect superclasses, as method inheritance bubbles down through the hierarchy.
Given that equals() is implemented by Object and Object is the direct or indirect superclass of every class, you don't have to provide an implementation for equals().

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.

Strange behavior observed in inheritence

I have an interface, IfcBase which is implemented by another class Base. This class is further extended by a second class SubBase. Further SubBase class implements another interface IfcNew. Both these interfaces have a method declared that has the same signature. Now SubBase does not define the method from IfcNew. I now create an instance of SubBase and assign it to the reference type IfcNew. I then invoke the lone method and get an output. The method from IfcBase was executed in this case. I believe this should not be allowed at some stage, either during compilation or execution. I fail to understand the behavior and solicit help. The source is below. Thanks a lot!
public interface IfcBase
{
public void printString();
}
public class Base implements IfcBase
{
public void printString()
{
System.out.println("Base Class");
}
}
public interface IfcNew
{
public void printString();
}
public class SubBase extends Base implements IfcNew
{
//
}
public class Test
{
public static void main(String[] args)
{
IfcNew i = new SubBase();
i.printString(); //Output:Base Class
}
}
This is how inheritance works in Java.
You have a method called public void printString() implemented in Base, from which you extend SubBase. As a result this implementation will be implicitly available in this class.
For the implements IfcNew part in the SubBase declaration, compiler will only check to see if SubBase has a method implemented which has the same signature as public void printString(). Since it implicitly inherits this implementation from Base, it has nothing to complain about.
This behavior can be easily understood if you look at it from OO design point of view. Please take a look at this article which I wrote few years ago. Look under the section called Method signature, Object Interface, Types, Subtypes and Supertypes. By the definition of subtype that is provided there, SubBase is already a subtype of IfcNew, so compiler has no problem with it.
This is the correct behavior of inheritance in Java.
There is no warning when implementing multiple interfaces with same-signature methods, because resolution takes place at runtime.
In this case, your SubBase class does not need to implement printString as its parent does, even if it isn't the "same" printString: the identical signature allows resolution at runtime.
This is obvious and not strange. This is because the method with same signature is already implemented in the base class and when you extend the base class it is automatically inherited. Now when you try to assign the object to IfcNew reference the method implemented is called which is not overriden in subclass, meaning that the base class method is called which actually is the implementation of IfcBase.

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.

Java using overriden methods

I am a noob and I need some help.
So I have this abstract class with a private variable. I also have a method named getThing() to return that.
I have a class that extends that abstract class, and it too has a private variable and a method that overrides the original to get the value from the abstract class.
Well the only way to be able to access both values is by creating a second method in the subclass called getSuperThing, and using the super in that. Well I was just wondering out of curiosity if there was some easier way to do that and be able to access the abstract classes method by doing something like objectNae.super.getThing().
Thanks ;)
The variable is private and so can only be referenced by the containing (abstract) class. As you have stated, from a subclass, you can invoke the superclass method (rather than the overridden one).
If you want to make the variable accessible from the subclass directly (without requiring the accessor method), make it protected instead. Here is the documentation on Controlling Access to Members of a Class.
If I understand your question correctly, then you just shouldn't override the abstract class' method in the concrete subclass. No need to, unless you need the subclass to return a different value than that returned by the abstract class (and that would suggest poor design).
Rather, the abstract class' method will be accessible as a method of the subclass.
So, if you have:
public abstract class AbstractClass {
private int value = 3;
public int getValue() {
return value;
}
}
public class ConcreteClass extends AbstractClass {
}
then you should be able to do:
new ConcreteClass().getValue()
I don't think you have other ways than calling super.getThing() in the subclass's getThing() or getSuperThing() method. Abstract class must be subclassed before being used.

Categories