*
The moose likes Beginning Java and the fly likes My first interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "My first interface" Watch "My first interface" New topic
Author

My first interface

miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
hi
i just made this:

i've heard a lot about oop's marvels;
so, i just created a Dog's instance called bibi of type Sound, instead of the usual:

is this correct?
is this one of the oop's wonders?
cant believe its so easy...
thanks in advance


java amateur
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

Yes, that's correct and it's so easy.
The real wonder is:
You may have a

Now you compile this.
You change your Main-class this way:

Compile and run.
That's not surprising.
But now you define a new Sound(able, to be conform, or Sounding, Soundible?)
called ... Penguin.
You create a Penguin 'tux' in main, add him to the chorus, and compile 'main' but don't compile 'Chorus'.
If you now run your application, tux will sing together with the others, i.e. it's 'itsSound ()' - method is called from a class, which was compiled prior to penguins definition.
I think that's surprising and a little bit a wonder
[ February 19, 2004: Message edited by: Stefan Wagner ]
(I hit the 'post'-button by accident to early - perhaps you only got a few lines)
[ February 19, 2004: Message edited by: Stefan Wagner ]

http://home.arcor.de/hirnstrom/bewerbung
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
sorry, but i'm not getting your point ...
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
when i try to compile, as you say to,i get this error:
C:\Java_Granel\Classes\Exercicios\Chorus.java:4: <identifier> expected
public Chorus {
^
C:\Java_Granel\Classes\Exercicios\Chorus.java:14: ';' expected
}
^
C:\Java_Granel\Classes\Exercicios\Chorus.java:3: cannot resolve symbol
symbol : class Vector
location: class Chorus
private Vector v;
^
3 errors
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I think one point that Stefan is trying to illustrate is that the Chorus class only knows that the objects in its list implement the Sound interface. It doesn't know the specifics about what sound each object makes. Still, when you call playAll(), the appropriate sound is made for each animal in the list.
Perhaps you can compile the code he gave to try to grasp how it works.
Layne


Java API Documentation
The Java Tutorial
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
It should be
public class Chorus
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Also, to use the Vector class you need to add the following line at the top of the file:
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
my code now is like this:

but i keep getting these error msgs:
C:\Java_Granel\Classes\Testes\Xpto.java:24: <identifier> expected
v = new Vector ();
^
C:\Java_Granel\Classes\Testes\Xpto.java:21: class Chorus is public, should be declared in a file named Chorus.java
public class Chorus {
^
C:\Java_Granel\Classes\Testes\Xpto.java:23: Chorus is already defined in unnamed package
public class Chorus {
^
C:\Java_Granel\Classes\Testes\Xpto.java:24: cannot resolve symbol
symbol : class v
location: class Chorus.Chorus
v = new Vector ();
^
C:\Java_Granel\Classes\Testes\Xpto.java:31: cannot resolve symbol
symbol : method itsSound ()
location: class java.util.Vector
System.out.println (v.itsSound ());
^
5 errors
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
I think one point that Stefan is trying to illustrate is that the Chorus class only knows that the objects in its list implement the Sound interface.

But, in that case, shoudnt Chorus class say:
implements MyInterface?
And something else:
maybe this is too advanced for me, but i see a class inside another, with the very same name...
[ February 19, 2004: Message edited by: miguel lisboa ]
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
well, i tried doing it separate files:

but keep geting this error msg:
C:\Java_Granel\Classes\Exercicios\Chorus.java:6: <identifier> expected
v = new Vector ();
^
C:\Java_Granel\Classes\Exercicios\Chorus.java:5: Chorus is already defined in unnamed package
public class Chorus {
^
C:\Java_Granel\Classes\Exercicios\Chorus.java:8: cannot resolve symbol
symbol : class Sound
location: class Chorus
public void add (Sound s) {
^
C:\Java_Granel\Classes\Exercicios\Chorus.java:6: cannot resolve symbol
symbol : class v
location: class Chorus.Chorus
v = new Vector ();
^
C:\Java_Granel\Classes\Exercicios\Chorus.java:13: cannot resolve symbol
symbol : method itsSound ()
location: class java.util.Vector
System.out.println (v.itsSound ());
^
5 errors

what am i doing wrong?
i'm anxious to marvel myself, though i guess i got the whole idea...
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

Sorry, but I didn't compile.
Of course you can not nest a class into itself.
The correction is:
public Chorus ()
{
// ... forgot round brackets

first of course:
import java.util.*;
and later I made silly mess in the Chorus:
// we need a Sound from the Vector:
Sound s = (Sound) v.get (i);
System.out.println (s.itsSound ());
here is the whole code - not best designed, because all in one File.
In real Life you would make seperate Files for all the classes and for the interface:
(this time I compiled it)

[ February 19, 2004: Message edited by: Stefan Wagner ]
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
excuse me but i getting more and more confused with the whole code.
Please help with the right code, ok?
one file:

get this error:
C:\Java_Granel\Classes\Exercicios\Nova pasta\Chorus.java:7: cannot resolve symbol
symbol : class Sound
location: class Chorus
public void add (Sound s) {
^
C:\Java_Granel\Classes\Exercicios\Nova pasta\Chorus.java:12: cannot resolve symbol
symbol : method itsSound ()
location: class java.util.Vector
System.out.println (v.itsSound ());
^
2 errors

the other file:
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

When editing too long questions and answers are crossing...
In the Iteration over the vector - loop (Chorus.playAll ()) is a big mistake.
I take a String from the Vector instead of sounds.
Another issue: I put it all into a single file, with public class Xpto, because it's got the main method.
And I implemented Penguin - don't want to post two Listings - it's long enough.
[ February 19, 2004: Message edited by: Stefan Wagner ]
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
In the Iteration over the vector - loop (Chorus.playAll ()) is a big mistake.
I take a String from the Vector instead of sounds.

so, how should i exactly have that piece of code?
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Stefan already posted the code so that it can compile. Either you can use it as is, or compare what you have so far with his to see what you might need to fix.
HTH
Layne
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
thanks a lot
i didnt realize there where an edit to code, so mine went on not compiling;
i'm used to fancier forums, in which one knows who's last poster, and so on, without having to re read the whole thread...
gonna read it/enjoy it right now!
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923


That's not a problem of the forum, but of the interaction with it.
I read your article.
Replied.
Someone told us about errors.
I started my response.
You started telling us about errors.
I finished my response, correcting the same errors, you were editing the same time.
Few seconds later you finished your question which was answered already, but not when you started your edit.
When I looked at the thread I saw, that your question appeared after my response.
Since answers aren't seen in realtime, while typing, you cannot avoid such asynchronous threads.
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
you'r right when saying its an interaction prob, but knowing who's last post is is a good thing; when waiting for aswrs in this post i answered in others, but i cant exactly remember which, and its a pitty... dont you agree? (should have a personal control for our posts/answers)
anyway i'm indeed marveled with interfaces.
my satisfaction was not possible without your good help!
thanks again
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

You're welcome.
And yes - it could be sorted so that last finished Posting is displayed last.
But if you allow the users to resort it, I guess it will end in a mess, and that might make it more complicated, to follow the thread.
boyet silverio
Ranch Hand

Joined: Aug 28, 2002
Posts: 173
Miguel,
I'd like to comment on the classes made. Please note that inheritance refers to a class/interface acquiring functionalities of another class/interface. This holds that both classes are on the same "footing" or category. One way to find out is to use the "is-a/n" test for inheritance (though this test is not complete). Applying this to the two classes involved in "inheritance", could one declare that the Dog "is-a" Sound? Or could one say that the Cat "is a" Sound"?
Or shouldn't it be that the Cat "is an" Animal, thus class Cat implements Animal? Or that the Dog "is a" Pet, hence class Dog implements Pet. It could just be in the naming of classes. But the naming of classes helps in clearly expressing the inheritance relationship. Try to look at sample classes out there which involves this relationship.
That's good effort though in creating your code.
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
thanks
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

To the question of 'is a', 'has a', ...
In this example, if the interface would have been called 'NoiseMaking', instead of 'Sound', we could clearly say: A dog implements 'NoiseMaking' or is a 'NoiseMakine' (as well as a BadSmellMaking - but that's another theme).
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
It might perhaps be easier to discuss a different example. Not to complicate things...



Now, based on the code above, I can write a method that doesn't even know whether I'm dealing with a Rectangle, a Circle, or some new shape that hasn't even been added to the system yet:

Also, note that I avoided implementing the same code in several places by using AbstractShape. (Incidentally, I'd write into the documentation for AbstractShape that no one, ever ever ever, should treat objects polymorphically as AbstractShapes. I would even make the entire class protected to prevent this sort of usage...but I'm not sure it's legal and I'm too lazy to look it up right now .)
By the way, should Square extend Rectangle? See what See what Martin thinks... over at Object Mentor. You'll probably want to read at least a few of the articles over there.
sev
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
Ugh...I made a number of simple mistakes in the last post from the "see what see what Martin thinks" to accidentally have backslashes in my [\code] tags. Is there going to be a way to preview posts to correct this sort of thing before long?
sev
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
wasnt AbstractShape class suposed to implement ALL interface's methods()?
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Sever Oon:
Ugh...I made a number of simple mistakes in the last post from the "see what see what Martin thinks" to accidentally have backslashes in my [\code] tags. Is there going to be a way to preview posts to correct this sort of thing before long?
sev

You can easily edit your post even after you've submitted it. Just click on the notepad-and-paper icon at the top of your message.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by miguel lisboa:
wasnt AbstractShape class suposed to implement ALL interface's methods()?

Since the "abstract" modifier is listed before the class name, it doesn't have to implement all of the methods. In fact, if this modifier were missing, I think it would be implied if any interface methods are not implemented. (Abstract classes are another topic, and it might be worth starting a new thread to discuss them.)
Layne
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
miguel--the purpose of the AbstractShape class is simply to act as a common code container for everything that would have to be rewritten for all of the classes that would implement Shape.
Think about it...how would you implement getPerimeter() in AbstractShape? You have the same problem there I was discussing in my post. How do you calculate the perimeter if you don't know whether you're dealing with a circle or a rectangle or a shape that hasn't been implemented yet?
sev
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
I may look dumb, but:
so ok for the abstract class, but what about those two other concrete ones: rect and circle?
Dont they have to implement those methods()?
the purpose of the AbstractShape class is simply to act as a common code container for everything that would have to be rewritten for all of the classes that would implement Shape.

Now i really got it, its a wonder, yes!
i wrote this to see it:

I'm very new to java, so excuse me this Q:
is there a way to see the maravilhoso() in action without making it static?
thanks in advance
[ February 26, 2004: Message edited by: miguel lisboa ]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
You could make the following changes:
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
Yes, that's it
Just a commentary:
in maths, one can write:
a * b + a * c, but its shorter writing:
a * (b + c).
I guess its the same here with the abstract class - it contains all the repeated code. Very elegant.
I just played around with code a bit and noticed all those gets and sets: is this good programming style, is this what they call encapsulation or else?
thanks in advance
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Get and set methods are common enough that they have more technical names: set methods are called accessors and set methods are mutators. This is another topic so I don't think I'll get into it here. Besides, you should be able to google either of these keywords to find more information about them.
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
ok, tx
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
Hey miguel--
I'm sorry if I was curt in my previous response, but time was a factor. No, just kidding (that joke was for anyone who's seen Pulp Fiction). Actually I just didn't realize it came off as a little brusque.
What I should have said is: when you write a class, it is the union of all data and methods contained in itself and all of its superclasses and superinterfaces. Access modifiers (public, protected, default, and private) may restrict access to those data members and methods, but they're still part of the class.
So if you look at Rectangle, for instance, when you create a new Rectangle instance:

rect has all of the methods it defines (getHeight(), getWidth()) as well as those defined by AbstractShape, Shape, and java.lang.Object (everything extends java.lang.Object if you don't specify some other class, so the methods and data defined therein are always available on every object).
When I first started using OO it was a little disorienting to see methods and data being accessed in an object that doesn't define them, but once you get used to it it's as natural as breathing. (Plus, javadoc has gotten better since those days so it actually does list all the methods that can legally be called on an object, including the inherited ones.)
Now a word about getters and setters--it is true they are given special privilege by the JavaBeans specification. IMHO, though, the good people at Sun kind of screwed this one up. I understand why *getters* have special recognition, because those methods can be used to define the exact behavior of a class (if the class is written properly). Setters, on the other hand, in my mind at least, are just methods like any other operation on a class.
Here's why a getter should be special...consider this class:

Now when you go to write the javadoc of this class, how do you write the doc for the increment method? What is the documentation supposed to say for this method? Most of the time, people will simply write something like: "increments the count". But this is not a very good definition of what the method does because let's say you're a unit tester, and you get this class and its doc. You want to verify that the class does what it says it does.
increment() says it "increments the count", but what does that mean? You might be able to figure it out because it's a fairly simple class, but I'm sure you can imagine working with a more complex class, or even for a company with its own vocabulary. What if, at your company, it is commonly known that "bump" means increment by 1, and the doc said instead "bumps the count". You might not know what that means your first day on the job.
Much better, though, is to write the documentation in terms of the properties of the class itself so that it is completely unambiguous as to what the method does: "Increments by 1 the result returned by getCount()." Now, this method is defined in terms of a property of the class--count--explicitly. If I have a class, and I call getCount(), then increment(), then getCount(), I can expect the second call to getCount() will yield a value one more than the previous call to getCount(). There is no ambiguity or company vocabulary that can impede the reader's understanding. setCount() can also be defined in terms of this property: "Changes the result returned by getCount() to c." (A very useful side benefit of this way of designing classes and writing documentation: it's easy to write unit tests because the assertions a unit test would make about this class almost write themselves.)
The problem with the JavaBeans spec, though, is it doesn't stop at defining a class property by getters. It also says that if a class lists a setXxx()-type method, whether a getter is present or not for Xxx, Xxx is now recognized as a "property". This is not as it should be, though...I can imagine a situation in which I need to use a setter but I do not wish to define a new property.
(I'm using the term "property" with a somewhat ambiguous special-ness attached to it. In OO theory, a property is defined as a special kind of element of a class. The set of properties of a class comprise the essential intrinsic nature of that class. If a class exposes a piece of data because that data is fundamental to the definition of that class, then that bit of data is a "property". This is an off-the-cuff explanation of the term, but I trust you get the point.)
For example, say I write a UserInfo class which contains a username and a password. I need the class to be mutable (the properties can be changed after instantiation), and I need to ensure that the class never enters into an inconsistent state (when one property is null (or empty string) and the other is not--so a user info object containing a username "foo" and null or empty string password is not allowed, and vice versa.)
How do I do this staying in the paradigm of JavaBeans getters and setters? Here's my first try:

Everything looks good--according to my design, I have two properties, and according to the JavaBeans spec, I have two properties: username and password. The only problem is, this class doesn't follow my rule about inconsistency. UserInfo objects should never be allowed to break my rule of one property being non-null if the other is null...but if you try to use this class, you quickly see that its design actually requires the caller to momentarily put it into an inconsistent state. Consider a scenario where I have a UserInfo instance that I need to put to a null state:

This is unacceptable. Furthermore, you'll see that if I leave the class API as it is, there's no way to fix it! I can't have it throw an exception in the code anywhere to ensure that the caller is settings things into a consistent state, because by writing the class this way I am requiring the user to momentarily set it to an inconsistent state. I cannot guarantee the consistency of the data...indeed, I *can* guarantee that it will be inconsistent at some point, which is the exact opposite of what I wanted. As the developer of this class, following the JavaBeans spec to the letter, I have to leave it up to the caller to make sure they keep these UserInfo objects consistent. This is called "quality by gentleman's agreement" and it doesn't work.
Much better if I break the JavaBeans spec and rewrite the class:

This is much better than the previous version. It guarantees that an exception will get thrown if the caller ever tries to put the class into a state where either username or password are empty strings or null. No more ensuring quality by gentleman's agreement.
According to my design, there are still only two properties of this class: username and password. But according to the JavaBeans spec, a third now exists: info. This is unfortunate because info does not really meet the definition of "property" according to OO theory--and there's no way to define info as a property because there's no way to get at the data that info represents. This new "property" is redundant, and therefore not fundamental to this class, because it doesn't exist separately from the other two defined properties on the class. To prove this, I can write the behavior of the setInfo() method completely in terms of the the username and password properties on the class...but what can the info property itself be used to define? Nothing...so in my mind, it's not really a property of the class in the OO sense and shouldn't be recognized as such.
One quick note about the class above--you might be wondering how I expect not to get NullPointerExceptions in my if statement. After all, I say (u==null || u.length()==0)...what if u is null? Then won't the runtime system throw an NPE when I call the length() method on a null reference?
The answer is no--because I put the null test on the left side of the logical OR "||", the runtime system performs that test first. If that returns true, then the JVM doesn't need to evaluate the other side--if one part of a logical OR is true, then the whole statement is true regardless of what the other side comes out to. This is called "logical short-circuiting" and is built into the language...just make sure you put the test you want performed first on the left side. You can see why this is useful if you examine the code above and consider how to perform these tests any other way and avoid NPEs--you'll quickly see how the code blows up to be somewhat more lengthy.
One final note: in case you haven't encountered it before, the ^ operator is the logical XOR--"eXclusive OR". It is true only if the two boolean operands are different. If the operands are both false or both true, then XOR'ing them yields false.
sev
[ February 27, 2004: Message edited by: sever oon ]
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
sev:
thanks a lot for your detailed and helpfull answer.
As you might have guessed i'm very new on java (just two numbers ahead you in these forums )
That means i'm not up to your qualified discussion on setters, getters and API documentation.
But i did read you carefully though i didnt had time to compile your code (i'll do it the moment i finish an interface oriented app i'm trying to write inspired on your shape example).
Hope i'll be back soon and thanks again
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: My first interface
 
Similar Threads
please explain the code and please anyone give example of overloading in enum
Casting to an Interface Type
generics
Problem with System.out.print
Illegal start of expression compilation error