aspose file tools*
The moose likes Beginning Java and the fly likes OOP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "OOP" Watch "OOP" New topic
Author

OOP

James Hambrick
Ranch Hand

Joined: Sep 04, 2004
Posts: 282

Don't understand some things gonna put them here and see if people can explain it to me.

first this code was in my book and it tries to explain upcasting



my questions is why do I have to call the tune method of Instrument? If Wind inherits Instrument shouldn't it have its own tune method?

2nd:
Abstract classes;
from what I read and understand, a class that is called abstract cannot be used. What's the point of making a class that cannot be used???

Interface:
I don't even have a clue as to what this is.


Visit my blog! http://jameshambrick.com
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11498
    
  16

a class that is called abstract cannot be used. What's the point of making a class that cannot be used??
not quite true. an abstract class cannot be instantiated. You can (and this is the point) derive a sub-class from it, fill in the missing bits, and 'use' that.

I don't even have a clue as to what this is.
Think of an interface as a contract. It is a list of methods that MUST be implemented. it's used for things like lists - I don't care HOW or WHAT the underlying object is, all i want is a List that will let me add(), remove(), and search(). as long as your class implements my List interface, I know I can call those methods on it.

Not only are you free to change the implemenation 'under the covers' as often as you want, but I can write my code to accept ANYTHING that implements my List interface. That means that while I'm sipping mai-tais on the beach in St. Thomas, my boss can sign a contract with a new vendor, they can implement my interface, and MY CODE WORKS, without me having to touch it.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
James Hambrick
Ranch Hand

Joined: Sep 04, 2004
Posts: 282

like the problem I had before where I used a mouselitener but I did not put all the methods in my program. I only wanted to use mousePressed, mouseClick and mouseRelease. But i got compile errors until I added them, even if I left the code inside it blank.
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
Thats because as Fred said an interface is a contract. By implementing an interface you are asserting that the implementing class will support *all* the methods listed in the interface. Say you have a method which accepts a MouseListener:



How would you know what methods were legal to call with the MouseListener passed as a formal parameter to the accept() method? Simple, you can call any method listed in the MouseListener interface.


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by James Hambrick:
...this code was in my book and it tries to explain upcasting...

It looks like this is from chapter 6 of Eckel's Thinking in Java, which is an excellent book, although parts of it can be rather challenging if you're a beginner.

I'm not sure which edition you're using, but I think you'll find that upcasting starts to make more sense over the course of the next couple of chapters. In fact, chapter 7 starts with a topic of "Upcasting Revisited." And interfaces in the sense that Fred and Garrett are taking about are not really introduced until the 8th chapter. (At least that's how the online 3rd edition is laid out. The 4th edition is different.)

Note that Eckel sometimes uses the word "interface" in an expanded sense. In addition to meaning a defined set of methods that must be implemented by a class (a "contract"), Eckel also uses "interface" to refer to an object's "visible" methods. That is, the different ways you can "interact" with an object. In the 1st chapter, "Introduction to Objects," he lays the foundation:
"...how do you get an object to do useful work for you? There must be a way to make a request of the object so that it will do something... The requests you can make of an object are defined by its interface..."

So in chapter 6, he's still using "interface" in a loose sense. Note the comment in the original post's code: "Wind objects are instruments because they have the same interface." But Instrument is a class that doesn't "implement" anything, and Wind simply extends (inherits from) Instrument.

So don't get frustrated working through these chapters. They throw a lot of terms and concepts at you, then take some time to pull all the pieces together.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
James Hambrick
Ranch Hand

Joined: Sep 04, 2004
Posts: 282

I have the 3rd edition, I read Upcasting revisited and still don't know why. In the example I have above why did he call instruent.tune(instrument i)? If Music inherits Instrument then shouldn't Music have a tune method from instrument by the inheritance? Did he do this just to show that it can be done, but no real reason to. He can't call wind.tune(Instrument i) can he? He has to call Instrument.tune(Instrument i) to tune it.



Also on upcasting revisited be uses the shape example. Circle, Square, Triangle inherit Shape. Then he creates a Circle like this
Shape s = new Circle(); Why??? just to show that it can be done?
[ July 26, 2007: Message edited by: James Hambrick ]
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11498
    
  16

Then he creates a Circle like this
Shape s = new Circle(); Why??? just to show that it can be done?

because after he did something with the circle, he could then do

s = new Square();
//do some stuff
s = new Triangle();
//do some stuff

etc.

for a trivial case like this, it looks silly. but perhaps you have a collection, like an array. You have to declare what goes into the collection. rather than making 5 arrays - one for each sub-class, you make an array of Shapes.

then, you can iterate through the entire array, calling the Shape methods (which you know exist), but due to polymorphism, the specific implementation for each subclass is what runs.
Anand Shrivastava
Ranch Hand

Joined: Jul 22, 2007
Posts: 125
On the interface, i was surfing the net and in one of the posts i found that interfaces can be used to glue several clases together i.e. if a particular class implements many interfaces then it is like multiple inheritance.

i could not follow the idea.

implementing many interfaces would mean writing your own code to implement the interface. Then when i have to write my own code under the methods, then what i have inherited from multiple classes.

kindly explain.


Anand Shrivastava
SCJA
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Anand Shrivastava:
... implementing many interfaces would mean writing your own code to implement the interface. Then when i have to write my own code under the methods, then what i have inherited from multiple classes...

The benefit is not in inheriting any functionality (implementation), but instead in acquiring a type. Going back to the contractual idea expressed above, if class A implements B, C, and D, then instances of type A are also types B, C, and D -- so they can be treated as any or all of these types, with confidence that the declared methods will be available.
Anand Shrivastava
Ranch Hand

Joined: Jul 22, 2007
Posts: 125
the concept would get more clear if we go by some code -

Let us say that there are following two classes:

Class One implements a
{
Method_one
{ // some code}
}

Class Two implements b
{
Method_two
{ // some code)
}

Class Derived implements a,b

{
Method_one
{ // no code just dumb implementation}

Method_two
{ // no code just dumb implementation}
}

Now if i make an object of Dervied class like this :

Derived object_derived;

Whether this object_derived will have access to method_one and method_two provided in the base classes or not.
And if this cannot have access to those methods and is just restricted to the methods of its class only,then what is the benefit of multiple inheritence ?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Anand Shrivastava:
...Whether this object_derived will have access to method_one and method_two provided in the base classes or not.
And if this cannot have access to those methods and is just restricted to the methods of its class only,then what is the benefit of multiple inheritence ?

Just to be clear, this is not multiple inheritance, and One and Two are not "base" classes. One and Two implement A and B respectively. Derived also happens to implement A and B, but this does not make it "derived" from One or Two. Instead, it only means that Derived shares some characteristics of One and some characteristics of Two.

But consider some other class with a method that takes a type B as an argument...

Now, because Derived implements B, an instance of Derived is also a type B. It's true that by implementing B, Derived did not inherit any implementation, but it did enter into a "contract" under which Derived must implement methodTwo. Therefore, if we have an instance of Derived, we can now pass it to the handleB method...

The code in handleB doesn't need to be concerned with how methodTwo is implemented, or even what the true runtime type of the argument is. Simply knowing that this instance implements B (and therefore IS-A B) means knowing that methodTwo will work as expected.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Anand Shrivastava:
...Method_one
{ // no code just dumb implementation}...

When you "implement" a method, that means you provide the code. Without code here, this method won't do anything.
Anand Shrivastava
Ranch Hand

Joined: Jul 22, 2007
Posts: 125
Now marc things are getting very interesting.

The moment we will pass the object of derived class in the handleB method, that object will have access to methodone and methodtwo both, i.e. that class in which we have passed this method will inherit the functionality of both classes class one and class two by virtue of this object - probably that is why it is called glueing the classes together and multiple inherience. Am i right ?
Anand Shrivastava
Ranch Hand

Joined: Jul 22, 2007
Posts: 125
the only rider being that we cannot get the benefit of the code of the method typed in original class, we will have to right our own code beneath the methods.

Anyway, thanks a lot for clearing my concept. If you can throw some more light on practical usage of multiple inheritance.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Anand Shrivastava:
... The moment we will pass the object of derived class in the handleB method, that object will have access to methodone and methodtwo both...

Not quite. The method handleB takes an argument of type B. So when we supply an instance of Derived as an argument to handleB, the reference is upcast to type B, and we can only call methods that are available in B (methodTwo). We would not be able to call methods defined in A (methodOne), or any other methods defined in Derived that are not in B.

So to illustrate the idea of gluing classes together using an interface, consider 4 different classes: Person, Jukebox, Bird, and Guitar. These might be completely unrelated, with different superclasses and different methods.

But now consider an interface...

If each of these 4 classes implement Singer, they now have something in common: They each must implement the method playSong. That's the "contract" they enter into when implementing the interface. Indeed, they ARE Singers.

Now if we have a method that takes Singer as an argument, we could pass instances of any of these 4 classes, and the method would treat them all the same -- as Singers. The method doesn't care what their true runtime type is -- whether the object is actually a Person, Jukebox, Bird, or Guitar -- or what additional functionality that object might have. All the method cares about is that the object IS-A Singer, and therefore has a playSong method.

For convenience, you can put the following all in a single file, then compile and run as GlueTheseTogether.

Now consider the flexibility we have here with this robust code. Our Chorus class works with Singers, without caring what the true types of the objects are. So in the future, someone else might develop a brand new class called Choir. And as long as Choir implements Singer, it will work perfectly fine in Chorus. No code in the Chorus class needs to be changed!
[ July 28, 2007: Message edited by: marc weber ]
Anand Shrivastava
Ranch Hand

Joined: Jul 22, 2007
Posts: 125
By your reply, it transpires that we can create arrays of type interface. Because Singer is an interface and you have created Singer[] arrayofsingers. This would contain the objects implementing that interface.

Moreover, when you call s.playsong(), the object of type bird will call the method of its class i.e. twe twe twe probably and person will call the method of its class i.e. na na na. Am i right ?

isnt this a kind of method overloading.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Anand Shrivastava:
By your reply, it transpires that we can create arrays of type interface. Because Singer is an interface and you have created Singer[] arrayofsingers. This would contain the objects implementing that interface...

Yes, an interface is a type. So, for example, an object that is type Person is also type Singer.

Originally posted by Anand Shrivastava:
... Moreover, when you call s.playsong(), the object of type bird will call the method of its class i.e. twe twe twe probably and person will call the method of its class i.e. na na na. Am i right ?

isnt this a kind of method overloading.

This is polymorphism, which has to do with overridding -- or in the case of interfaces, implementation. The method body that's invoked is determined by the true runtime type of the object.

Obviously, Singer itself has no implementation (because it's an interface). But when playSong is called on a Singer, the playSong method that's invoked is determined by the true type of the object (e.g., Person, Bird, etc.).
Anand Shrivastava
Ranch Hand

Joined: Jul 22, 2007
Posts: 125
Thanks marc for clearing things up.

If you dont take me otherwise, please reply to my thread help on studies lying in this forum. Though Stan has made his suggestions, but he has left some points. If you can just find time to meticulously reply to it, i would be grateful.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Anand Shrivastava:
Thanks marc for clearing things up.

If you dont take me otherwise, please reply to my thread help on studies lying in this forum. Though Stan has made his suggestions, but he has left some points. If you can just find time to meticulously reply to it, i would be grateful.

Thanks for asking, but I don't have much expertise in EE, so I think Stan has already replied in greater detail than I could.
James Hambrick
Ranch Hand

Joined: Sep 04, 2004
Posts: 282

Animal d = new Dog();

I should step back a minute and look at this.
It creates a dog obect with an animal reference but what does this actually mean? What does Animal reference mean?
James Hambrick
Ranch Hand

Joined: Sep 04, 2004
Posts: 282

Does it just mean that Dog is a type of animal??? someone anyone...
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Yes, Dog is a type of Animal. The line...

Animal d = new Dog();

...creates a new object that is a Dog, and the variable 'd' is assigned a reference to that object. But the variable has a type of Animal, so the reference is upcast to type Animal.

At that point, 'd' is treated like an Animal. You can call Animal methods on it, pass it to a method that takes Animal as an argument, put it in an array or collection of type Animal, etc. But underneath it all, the object is still a Dog. So when you call Animal methods on it, the Dog versions of these methods will be invoked (assuming these methods are overridden or implemented in the Dog class), so this instance of Animal will behave like a Dog.

This allows other developers to write code that works with Animals without having to worry about what subtype of Animal they're dealing with. It might even be an Animal that's not yet discovered (code that's not yet written).

Without polymorphism, AnimalHospital would need code specific to each type of Animal, and would need to be updated whenever a new type of Animal is discovered...
Anand Shrivastava
Ranch Hand

Joined: Jul 22, 2007
Posts: 125
yes it does means that

This is a key concept of polymorphism

Animal is the base class.
Dog is the extended class adding more functionality to it.
The play method lies in both the classes.

when we write Animal d = new dog();
an object of type Animal is created instantiated by the dog class.
i.e. when you will call d.play() the play method of dog class will be operated.

The benefit here is

suppose we have two more classes like this

Class cat extends animal {
void play()
{
system.out.prinltn("cat is playing");
}
+ some more methods to extend the functionality
}

Class mouse extends animal {
void play()
{
system.out.println("Mouse is playing");
}
+ certain other methods
}

and now if we make a class like this

class playanimals {
playanimals(Animal animaltypeobject)
animaltypeobject.play();
}

class allanimalsplay()
{
Static void main(String[] args)
{
for (i=0;i<>3<>i++)
{
switch i
case 0 : Animal a = new dog();
break;
case 1 : Animal a = new cat();
break;
case 2 : Animal a = new mouse();
break;
playanimals p = playanimals(a);
}
}
}

exact play methods would be called. Note that we are only passing animal type object to playanimals and it is playing the right method depending upon the subclass from which the object is instantiated.

But Marc one question for you
when we say Animal a = new dog (d) will this a object have access to bark method which is specific to dog class or it will be restricted to play method only which is in its parent class. Correct me if i have explained something wrongly. I suppose it should have access to bark method as well.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Anand Shrivastava:
...when we say Animal a = new dog (d) will this a object have access to bark method which is specific to dog class or it will be restricted to play method only which is in its parent class...

When a reference is upcast, only the methods defined in that supertype are "exposed."

An Animal does not have a bark method, so we should not expect to be able to call animal.bark(). On the other hand, an Animal might have a makeSound() method, which could be implemented in Dog to bark.
 
 
subject: OOP