markzzz
markzzz

Reputation: 47995

Java - Problem with abstraction

I have this trouble. Im working with some library, and i need to create an istance of a class that is an interface.

In fact, i need to send it trought a function. But with first method i can't, or i don't know how to get the variable for that class. How can I pass it?

I need somethings like area=this.createITextArea(), so i can use the variable area in the function...

Hope the question is clear...

Upvotes: 0

Views: 143

Answers (4)

Jules
Jules

Reputation: 1371

Despite the question being a bit unclear:

E.g.:

ITextArea area = this.createITextArea();
someObj.someMeth(area);

or inline:

someObj.someMeth(this.createITextArea());

I'd recommend further reading on Java Interfaces.

Upvotes: 3

Andreas Dolk
Andreas Dolk

Reputation: 114797

An instance of a class is never an interface. A method may return an interface type, but the "thing", that you get through the method, is always an object which implements this interface.

Some simple examples to illustrate it:

public static main(String[] args) {
  List list = createList();
}

public static List createList() {
  return new ArrayList();
}

The createList method returns an interface type (List) but it returns an instance of a real class (ArrayList). So at the end, the local variable list holds a reference to this instance of ArrayList.

Back to your example: Assuming you have an interface

public interface ITextArea { /* methods */ }

and want to create an object "that implements this interface", then you need another class like

public class TextArea implements ITextArea { /* methods */ }

and you'll want to create instances of this concrete class.

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346377

So what's the problem with this:

ITextArea area = this.createITextArea();

?

Upvotes: 4

GaryF
GaryF

Reputation: 24360

You do NOT need to create an instance of an interface. You need to create an instance of a class which implements said interface. Find or write such an implementation, instantiate that, and then assign it to your variable.

Upvotes: 2

Related Questions