Forums Register Login

My first interface

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
sorry, but i'm not getting your point ...
+Pie Number of slices to send: Send
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

 
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
It should be
public class Chorus
+Pie Number of slices to send: Send
Also, to use the Vector class you need to add the following line at the top of the file:
+Pie Number of slices to send: Send
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

 
+Pie Number of slices to send: Send
 

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 ]
+Pie Number of slices to send: Send
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...
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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:
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
 

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?
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send

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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
thanks
+Pie Number of slices to send: Send
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).
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
wasnt AbstractShape class suposed to implement ALL interface's methods()?
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
 

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
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
You could make the following changes:
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
ok, tx
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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
Forget this weirdo. You guys wanna see something really neat? I just have to take off my shoe .... (hint: it's a tiny ad)
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1717 times.
Similar Threads
Problem with System.out.print
Illegal start of expression compilation error
Casting to an Interface Type
generics
please explain the code and please anyone give example of overloading in enum
Does an "if" statement change the time complexity of function?
instanceof operator with interface
invalid cast exception
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 11:54:23.