Can we have constructor in interface in java

Constructor in an Interface?

In your case the interface allows class D to talk to classes A, B and C, and possibly to many other interface implementations that you can be even unaware of. Solution 1: The huge advantage of using an interface type in a method (or constructor) parameter is that other programmers can call it and pass in their own classes that implement the interface.

Constructor in an Interface?

I know it’s not possible to define a constructor in an interface. But I’m wondering why, because I think it could be very useful.

So you could be sure that some fields in a class are defined for every implementation of this interface.

For example consider the following message class:

public class MyMessage < public MyMessage(String receiver) < this.receiver = receiver; >private String receiver; public void send() < //some implementation for sending the mssage to the receiver >> 

If a define an interface for this class so that I can have more classes which implement the message interface, I can only define the send method and not the constructor. So how can I ensure that every implementation of this class really has an receiver set? If I use a method like setReceiver(String receiver) I can’t be sure that this method is really called. In the constructor I could ensure it.

Taking some of the things you have described:

«So you could be sure that some fields in a class are defined for every implementation of this interface.»

«If a define a Interface for this class so that I can have more classes which implement the message interface, I can only define the send method and not the constructor»

. these requirements are exactly what abstract classes are for.

A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time . When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.

interface Named < Named(String name); >interface HasList < HasList(List list); >class A implements Named, HasList < /** implements Named constructor. * This constructor should not be used from outside, * because List parameter is missing */ public A(String name) < . >/** implements HasList constructor. * This constructor should not be used from outside, * because String parameter is missing */ public A(List list) < . >/** This is the constructor that we would actually * need to satisfy both interfaces at the same time */ public A(String name, List list) < this(name); // the next line is illegal; you can only call one other super constructor this(list); >> 

An interface defines a contract for an API, that is a set of methods that both implementer and user of the API agree upon. An interface does not have an instanced implementation, hence no constructor.

The use case you describe is akin to an abstract class in which the constructor calls a method of an abstract method which is implemented in an child class.

The inherent problem here is that while the base constructor is being executed, the child object is not constructed yet, and therfore in an unpredictable state.

To summarize: is it asking for trouble when you call overloaded methods from parent constructors, to quote mindprod:

In general you must avoid calling any non-final methods in a constructor. The problem is that instance initialisers / variable initialisation in the derived class is performed after the constructor of the base class.

A work around you can try is defining a getInstance() method in your interface so the implementer is aware of what parameters need to be handled. It isn’t as solid as an abstract class, but it allows more flexibility as being an interface.

However this workaround does require you to use the getInstance() to instantiate all objects of this interface.

Java — Passing an interface object in a constructor as an, It is perfectly acceptable to declare an argument to a constructor or method that is an interface type. In fact that is a good practice. public Simulator (Factory theFactory) < this.factory = theFactory; this (DEFAULT_DEPTH, DEFAULT_WIDTH); sane (); >In this case, you should declare you animalFactory …

Java interface with constructor in implementation class

I have a rather basic question about interfaces, something I’m rather new too. I typically would instantiate my class with an overloaded constructor . I’m now trying to use interfaces and wondering how I would populate my constructor. Would I just use something like setSomeMethod(arguement1, arguement2) in my interface to populate my attributes?

I’d also like to note I’m using «Tapestry5» framework with service Injection. Example

public class MountainBike implements bicycle < private String arg1; private String arg2; public MountainBike() < //Assuming there is no way to overload this constructor >public void someMethod(String arg1, String2 arg2) < this.arg1 = arg1; this.arg2 = arg2; >> 

Then how do you handle extended classes? I’m not sure how to populate the extended class constructor.

public class MountainBike extends BicycleParts implements bicycle < private String arg1; private String arg2; public MountainBike() < //Assuming there is no way to overload this constructor //Not sure where to put super either, but clearly won't work here. //super(arg1); >public void someMethod(String arg1, String2 arg2) < this.arg1 = arg1; this.arg2 = arg2; //Assuming it doesn't work outside of a constructor, so shouldn't work //here either. //super(arg1); >> public class BicycleParts < private String arg1; public void BicycleParts(String arg1) < this.arg1 = arg1; >> 

First off, your bicycle method should be declared with a return type :

public void someMethod(String arg1, String arg2); 

Interfaces define a contract for methods and not how objects are instantiated. They can also define static variables.

To use someMethod in your MountainBike constructor, you could make the call in the constructor:

public MountainBike(String arg1, String arg2)

Wrt, your question on extending the class, the super statement must appear as the very first statement in the constructor i.e.:

public class MegaMountainBike extends BicycleParts implements bicycle < public MegaMountainBike() < super("Comfy Saddle"); // do other stuff >

You seem to be confused. Java the language defines constructors and methods. Constructors have special restrictions and cannot be put in an interface, and are implicitly called whenever you do a new statement. Since constructors cannot be placed in interfaces, the common practice is to use factory methods instead.

Java interface type as constructor parameters, The huge advantage of using an interface type in a method (or constructor) parameter is that other programmers can call it and pass in their own classes that implement the interface. Classes that you didn’t know about and which didn’t even exist when you wrote the method/constructor.

Can we define constructor inside an interface in java?

No, you cannot have a constructor within an interface in Java.

  • You can have only public, static, final variables and, public, abstract, methods as of Java7.
  • From Java8 onwards interfaces allow default methods and static methods.
  • From Java9 onwards interfaces allow private and private static methods.

Moreover, all the methods you define (except above mentioned) in an interface should be implemented by another class (overridden). But, you cannot override constructors in Java.

Still if you try to define constructors in an interface it generates a compile time error .

Example

In the following Java program, we are trying to define a constructor within an interface.

public interface MyInterface< public abstract MyInterface(); /*< System.out.println("This is the constructor of the interface"); >*/ public static final int num = 10; public abstract void demo(); >

Compile time error

On compiling, the above program generates the following error

Output

MyInterface.java:2: error: expected public abstract MyInterface(); ^ 1 error

In short, it does not accept methods without return type in an interface. If you add return type to the MyInterface() method then it is considered as a normal method and the program gets compiled without errors.

public interface MyInterface

Java — How to have a constructor that accepts, A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. Then you can pass in an implementation of your AlertDAO-interface to the constructor of your AlertService-class, when you are creating an object of it in any other class. …

Java interface type as constructor parameters

hi i am learning about Java interfaces. I read in Java tutorial that an interface is a reference type. Say I declare an interface

and i have 3 classes, class A<>, B<> and C<>.

class A<> implements INT. class B<> extends A<> and implements INT. class C<> implement INT. 

then i have another class D<> that has constructor

and then in main(), i instantiate a D object

D myobject = new D( new A(), new B(), new C() ); 

It is said that objects that are not related by class hierarchy can be used to interact with each other using interface. So in the above class, class C and A are not related and now the interface allows them to «talk» to each other? am i understanding this correct? what other advantages is there to declaring the constructor to be of interface type instead of the actual class type , as opposed to

private A a, B b, C c ; public D( A a1, B b1 , C c1)

Is it something to do with polymorphism? sorry, this is my first attempt at OO, so am lacking some understanding here.

The huge advantage of using an interface type in a method (or constructor) parameter is that other programmers can call it and pass in their own classes that implement the interface. Classes that you didn’t know about and which didn’t even exist when you wrote the method/constructor. If you use concrete classes, callers have to use those classes, subclass them or change your code, all of which restrict them much more than implementing an interface.

Your code is absolutely correct.

The advantage of using interface instead of real class is that you expose only the communication interface of the object and not the way the object is implemented. It allows you to change the implementation in any time without breaking the client code.

This thing is called encapsulation: hiding the implementation details from the outside of the class. It is always a good thing.

About communication: they can’t communicate directly. But you can call method dosomething on any of the passed objects, because they all implement the same interface. So, somewhere inside object D you can write:

a1.dosomething(); // called the method of A b1.dosomething(); // called the method of B c1.dosomething(); // called the method of C 

It is not clear what you mean by «class C and A are not related and now the interface allows them to «talk» to each other», but your code looks correct.

So in the above class, class C and A are not related and now the interface allows them to «talk» to each other?

Not exactly. You seem to understand the whole thing correctly, but this part is vague. It’s not that interface allows them to talk to each other, it allows everyone to talk to them in a uniform way, without even knowing what classes represent a particular interface in a particular case. Of course, «everyone» includes those classes as well, so they can talk to each other too, so you are not wrong, but that’s just irrelevant. In your case the interface allows class D to talk to classes A, B and C, and possibly to many other interface implementations that you can be even unaware of.

An interface defines what an object can do. A class defines how it does that. It is called separating implementation from interface. Polymorphism is a mechanism that allows this. When you call an interface method and an implementing class method is called, it’s polymorphism.

Can Java interfaces have constructors?, Unlike say C#, Java’s interfaces cannot prescribe a constructor. What you are doing in your code is creating an anonymous class that extends java.lang.Object (which does have a default constructor) and implementing the interface. What you have instantiated is an Anonymous Inner Class. In short, it’s …

Источник

Читайте также:  Python re search ignore case
Оцените статью