I'm working on a java exercise that has me a bit confused. How can I use polymorphism while the methods are in an interface? Some help would be appreciated.
Setters and getters can be omitted.
What I have so far:
Interface:
interface Interface {
public void start();
public void stop();
}
First Class:
class Class1 implements Interface {
private String brand;
#Override
public void start() {
System.out.println("Hello from start"); }
#Override
public void stop() {
System.out.println("Hello from stop");}
}
Class 2:
class Class2 implements Interface {
private String plate;
#Override
public void start() {
System.out.println("Hello from start");
}
#Override
public void stop() {
System.out.println("Hello from stop");}
}
Aggregation Class:
class Aggregate {
private String destination;
private String starting;
public void trip(interface : Interface) {
interface = new Aggregate(Interface);
}
}
An interface in java, is a collection of abstract methods. When a class implements an interface, it inherits the abstract methods of the interface, so that the class can add a body to those methods specifically for itself. In other words, the class can override those methods mentioned in the interface. I believe you know that overriding and overloading are two types of polymorphism in java. So, in your answer above, you have indeed used polymorphism correctly. Just, add a simple method body relevant to the class, like printing something to the screen (as mentioned in the assignment), in order to add more meaning.
Related
I have got multiple classes which each implement multiple different methods within each. Now the problem statement is that I wish to use the methods from all these (maybe around ~200 such different class files/methods) in another class file which all different methods from the above class files.
I thought that if I implement an interface which has all these various methods listed, then I just call/import/reference that single interface and can use all the methods? But I am stuck, as this solution does not seem to work.
The opposite of the above works (i.e. single class implements 2 interfaces: http://tutorials.jenkov.com/java/interfaces.html). Wish to check if the single interface can use multiple classes, without the overhead of declaring all the methods in each class that is being referenced inside the Interface?
As an example: Is there any way in which I can implement 2 different classes in the same interface, without each having the abstract class for each? As if the class is abstract, then I am unable to use the methods from it in the below example "Application" class:
Common commonClass = new ABC_FamilyGivenName();
The above is not allowed, if the ABC_FamilyGivenName class is an abstract class.
INTERFACE:
public interface Common {
void ABC_GivenNames();
void ABC_FamilyNames();
void ABC_Gender();
void ABC_BirthDay();
}
IMPLEMENTATION CLASSES:
public class ABC_FamilyGivenName extends Base implements Common {
public void ABC_GivenNames(){
// Implementation code
}
public void ABC_FamilyNames(){
// Implementation code
}
}
public class ABC_DOBGender extends Base implements Common {
public void ABC_Gender(){
// Implementation code
}
public void ABC_BirthDay(){
// Implementation code
}
}
USE IMPLEMENTED CLASS:
public class Application extends Base {
Common commonClass = new ABC_FamilyGivenName();
/* DO I NEED THIS? I THINK I DO, BUT CODE/JAVA SAYS I DO NOT
* Common commonClass = new ABC_DOBGender();
*/
public void ELP_C0050_PassportDetails(){
commonClass.ABC_GivenNames();
commonClass.ABC_FamilyNames();
commonClass.ABC_DOB();
commonClass.ABC_Gender();
}
}
I have 2 classes called ABC_FamilyGivenName & ABC_DOBGender.
I have created an interface Common.
I want to use the methods in both the above classes in another class called Application.
With the current implementation, Java wants me to add an #Override to both the ABC_FamilyGivenName & ABC_DOBGender:
IMPLEMENTATION CLASSES:
public class ABC_FamilyGivenName extends Base implements Common {
public void ABC_GivenNames(){
// Implementation code
}
public void ABC_FamilyNames(){
// Implementation code
}
#Override
public void ABC_BirthDay() {}
#Override
public void ABC_Gender() {}
}
public class ABC_DOBGender extends Base implements Common {
public void ABC_Gender(){
// Implementation code
}
public void ABC_BirthDay(){
// Implementation code
}
#Override
public void ABC_GivenName() { }
#Override
public void ABC_FamilyName() { }
}
Can I avoid the above #Override and just use the classes without these as given in the first example?
Object-oriented programming in Java requires to "override" all methods, if you are implementing a method, otherwise you may use inheritance, so not all methods must be overriden.
In your case you may put all four methods to parent class Base and then inherit them.
Then the interface class is not needed or make two different interfaces.
To implement Java interface, You should override all the abstract methods are declared into the interface. It is a basic concept of interface. Here interface Common all four methods are abstract, So you should override them. Otherwise, Java compiler will throw a compilation error. So better way can be splitting the interface into 2 parts.
It is a contractual nature of an interface the subclass who implement the interface should have all the activities of the interface. It is the main purpose of using an interface.
If you don't wanna override all the method of interface but you need to use the interface as a reference of every class, then you can use a concrete class instead of interface and inherit the concrete class to every class
To implement the below code change please make sure you use java8
public interface Common {
default public void ABC_GivenNames() {
}
default public void ABC_FamilyNames() {
}
default public void ABC_Gender() {
}
default public void ABC_BirthDay() {
}
}
IMPLEMENTATION CLASSES:
public class ABC_FamilyGivenName extends Base implements Common {
public void ABC_GivenNames(){
// Implementation code
}
public void ABC_FamilyNames(){
// Implementation code
}
}
public class ABC_DOBGender extends Base implements Common {
public void ABC_Gender(){
// Implementation code
}
public void ABC_BirthDay(){
// Implementation code
}
}
Can I avoid the above #Override and just use the classes without these
as given in the first example?
No, in java you have to implement all methods of interface unless its abstract class
as suggestion you can create two separate interfaces,
for more detail see : not implementing all of the methods of interface. is it possible?
You can provide an empty implementation for all the methods of an interface in other class called Adaptor class. And you can extend that adaptor class in ABC_FamilyGivenName class and ABC_DOBGender class.
class Adaptor implements common
{
public void ABC_GivenNames() {
}
public void ABC_FamilyNames() {
}
public void ABC_Gender() {
}
public void ABC_BirthDay() {
}
}
IMPLEMENTATION CLASSES :
public class ABC_FamilyGivenName extends Adaptor{
public void ABC_GivenNames(){
// Implementation code
}
public void ABC_FamilyNames(){
// Implementation code
}
}
public class ABC_DOBGender extends Adaptor {
public void ABC_Gender(){
// Implementation code
}
public void ABC_BirthDay(){
// Implementation code
}
}
interface Icalculate{ //interface
calculate(operand1:number,operand2:number):number
}
class Add implements Icalculate{ //addition
calculate(operand1: number, operand2: number): number{
return (operand1 + operand2);
}
}
class Sub implements Icalculate{ //subtraction
calculate(operand1: number, operand2: number): number{
return (operand1 - operand2);
}
}
class Mul implements Icalculate{ //multiplicationn
calculate(operand1: number, operand2: number): number{
return(operand1*operand2);
}
}
class Div implements Icalculate{ //Division
calculate(operand1: number, operand2: number): number{
return(operand1/operand2);
}
}
let a = new Add;
let b = new Sub;
let c = new Mul;
let d = new Div;
class Calculator { //main class
operator: Icalculate;
operand1: number;
operand2: number;
constructor(a: number, b: number, operator: Icalculate) {
this.operand1 = a;
this.operand2 = b;
this.operator = operator;
let op = this.operator;
console.log(op.calculate(this.operand1, this.operand2));
}
}
const cal=new Calculator(1,1,a);
I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :
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
}
I have a small set of methods from various classes that I'm exposing through a proxy-like convenience class. My issue is that one of those methods takes as an argument an instance of a class implementing an inner interface. I however, do not want to expose that interface through the original class, and would rather provide it through my proxy.
Here is an example of what I mean:
Class C1 {
public static void addSomeListener(SomeListener listener) {
// Some code
}
public interface someListener {
public void interfaceMethod();
}
}
Class C2 {
public interface someListener {
public void interfaceMethod();
}
public static void doAddListener(SomeListener listener) {
// The compiler, of course, complains here
C1.addSomeListener(listener);
}
}
I'm wondering if it's possible to somehow "override" that interface so that the interface from C2 can be exposed to the user/developer while still keeping the inner interface defined in C1 hidden.
The following should do the job:
class C2 {
public interface SomeOtherListener extends SomeListener {
public void interfaceMethod();
}
public static void doAddListener(SomeOtherListener listener) {
C1.addSomeListener(listener);
}
}
I'm looking to create a set of functions which all implementations of a certain Interface can be extended to use. My question is whether there's a way to do this without using a proxy or manually extending each implementation of the interface?
My initial idea was to see if it was possible to use generics; using a parameterized type as the super type of my implementation...
public class NewFunctionality<T extends OldFunctionality> extends T {
//...
}
...but this is illegal. I don't exactly know why this is illegal, but it does sort of feel right that it is (probably because T could itself be an interface rather than an implementation).
Are there any other ways to achieve what I'm trying to do?
EDIT One example of something I might want to do is to extend java.util.List... Using my dodgy, illegal syntax:
public class FilterByType<T extends List> extends T {
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
}
You can achieve something like this using a programming pattern known as a 'decorator' (although if the interface is large then unfortunately this is a bit verbose to implement in Java because you need to write single-line implementations of every method in the interface):
public class FilterByType<T> implements List<T> {
private List<T> _list;
public FilterByType(List<T> list) {
this._list = list;
}
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
// Implement List<T> interface:
public boolean add(T element) {
return _list.add(element);
}
public void add(int index, T element) {
_list.add(index, element);
}
// etc...
}
Alternatively, if the methods don't need to access protected members, then static helper methods are a less clucky alternative:
public class FilterUtils {
public static void retainAll(List<T> list, Class<?> c) {
//..
}
public static void removeAll(List<T> list, Class<?> c) {
//..
}
}
What prevents you from just adding new methods to the interface?
If you can't just add the new functionality to old interface, you could consider making another interface and then an implementation which merely implements those two. Just to be clear, in code this is what I mean:
// Old functionality:
public interface Traveling {
void walk();
}
// Old implementation:
public class Person implements Traveling {
void walk() { System.out.println("I'm walking!"); }
}
// New functionality:
public interface FastTraveling {
void run();
void fly();
}
// New implementation, option #1:
public class SuperHero extends Person implements FastTraveling {
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
// New implementation, option #2:
public class SuperHero implements Traveling, FastTraveling {
void walk() { System.out.println("I'm walking!"); }
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
I think it's illegal because you can not guarantee what class T will be. Also there are technical obstacles (parent's class name must be written in bytecode, but Generics information get lost in bytecode).
You can use Decorator pattern like this:
class ListDecorator implements List {
private List decoratingList;
public ListDecorator(List decoratingList){
this.decoratingList = decoratingList;
}
public add(){
decoratingList.add();
}
...
}
class FilterByArrayList extends ListDecorator {
public FilterByAbstractList () {
super(new ArrayList());
}
}
There is a delegation/mixin framework that allows a form of this. You can define a new interface, implement a default implementation of that interface, then request classes which implement that interface but subclass from elsewhere in your hierarchy.
It's called mixins for Java, and there's a webcast right there that demonstrates it.
I'm afraid it's not clear what do you want to get.
Basically, I don't see any benefit in using 'public class NewFunctionality<T extends OldFunctionality> extends T' in comparison with 'public class NewFunctionality extends OldFunctionality' ('public class FilterByType<T extends List> extends T' vs 'public class FilterByType<T> implements List<T>')