Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

How can an Interface like AppletContext show a document ?

  Asked By: Bailey    Date: Apr 28    Category: Java    Views: 873

An example I have seen in a book uses AppletContext to show a
document as follows :

AppletContext ac = getAppletContext();
ac.showDocument(url); // url is declared in the code

Now AppletContext is an Interface and not a Class. As such, it's
methods (including showDocument) are only declarations and need to be
implemented by a Class. Only the showDocument() method of such a
class implementing AppletContext can be used to show a document.

Yet the example directly invokes the showDocument() method from the
Interface itself.

Is this really possible and if so how ?



2 Answers Found

Answer #1    Answered By: May Hansen     Answered On: Apr 28

can you please post the getAppletContext() method  ?...

Answer #2    Answered By: Abana Cohen     Answered On: Apr 28

...and there exactly seems to be some misunderstanding by the OP.
Have a look at the first line you've posted:

AppletContext ac = getAppletContext();

Have a sharp look: ac is defined as a _reference_ to some object
which belongs to some class; the only thing that is required from
this class  is that it implements the interface  AppletContext.
After this reference ac has been declared, ac is set to whatever the
method getAppletContext() returns; I suppose (I'm too lazy to check
the JavaDoc) that this method  creates some object which implements
the interface AppletContext, so this assignment is perfectly alright.

In other words: suppose you need to use some method xxx() which is
defined in an interface MyInterface. And suppose that you have one or
more classes Class1, Class2, Class3 which all implement this
interface MyInterface.
Then you have two different ways to declare something which allows
you to call for example  method Class3.xxx():

Class3 c = new Class3();

2) MyInterface c = new Class3();

Obviously the first method is very direct and easy to understand. But
imagine that some day in the future you'll have to switch from Class3
to Class1 in this particular circumstance. Then you have to change
two things at once, namely by writing

Class1 c = new Class1();

Believe it or not, but there have been enough cases where the poor
chap who had to change this changed the "new Class1()" but forgot to
change the "Class3 c" to "Class1 c". What happened? Of course the
compiler refused to compile this, which means once more editing the
source code...

In the end it's more a matter of taste which method you prefer, but
both have their advantages and disadvantages. The biggest
disadvantage of the second approach you already discovered: it's easy
to puzzle newbies this way; this happened to me as well. :-)

Hope this helps.

Didn't find what you were looking for? Find more on How can an Interface like AppletContext show a document ? Or get search suggestion and latest updates.