multiple inheritance casting , constructor chaining [duplicate] - java

This question already has answers here:
Java Multiple Inheritance
(17 answers)
Closed 8 years ago.
I have gone through various sites to understand java does not support multiple inheritance. One of the reasons was to avoid issues like casting and constructor chaining. How does multiple inheritance would cause the issue of casting and constructor chaining in Java? Can anybody explain me with example.

There are multiple reasons why multiple inheritance could be an issue, and to prevent these, Java simply does not allow it at all. The main one is diamond inheritance aka the diamond problem. Lets say you have superclass animal, and subclasses land and water. Now, lets say you create another class, frogs. Because frogs can live in water, or on land, you decide that the frog class will inherent from both land and water. So it will be a subclass of land and water.
Lets extend our scenario to say that the animal class has a move method. This method has the animal traveling a distance without specifying how they do so. The land subclass overrides this move method to specify that the animal is walking. Meanwhile, the water subclass overrides to specify that the animal is swimming. If a frog were to try to move, it would not know whether it was swimming, or walking. This can cause some serious issues, and is the basic problem to which EJP was referring.

Related

About class and object relationship [duplicate]

This question already has answers here:
The difference between Classes, Objects, and Instances
(16 answers)
Closed 4 years ago.
Can I say that class is a manual for building up an object?
I agreed that object is one of the instance of class.But if some properties that defined by classes may not make sense for particular object, for example,I have an object called "Duck" which use the class "Bird" for build, but Duck cannot fly,so if I use class "Bird" for build up an object "Duck".In the other words, the manual cannot provided the guideline for build up the object.
So,can i say that class is a manual for building up an object?As well as the manual should provided all the functions that the users need,in case there shouldn 't have any defects inside.
You are mixing two things at the same time:
On one hand you have to know that a class is just some kind of a template for an object instance, as it will show you what are the attributes and methods that any instance of that object can do. For example, you can think about the class "Car". Each car will have a different colour and a different plate number. That's a good sign for us to think that those two can be attributes of the class.
On the other hand, you have to know that sometimes classes are related between them and you have some tools to resolve your problems. That's when inheritance and interfaces come along in your example. As you can imagine, any duck is a bird, but not any birds are ducks. Therefore, you can establish a class inheritance between Bird (as a "father" class) and Duck (as a "child" class), because a lot of the behaviour between birds can be defined for all of them. In your specific example, you will define the "flying" methods in Bird subclasses.
Moreover, you can say that this example should have Bird as an abstract class, because Bird is a "concept" but it cannot exist by itself (you can also think in "polygon" and "triangle", polygon doesn't make sense by itself).

Interfaces and methods in Java [duplicate]

This question already has answers here:
Is there more to an interface than having the correct methods
(17 answers)
Closed 7 years ago.
For Java!!
We can implement different methods in different classes. In interface we create an abstract method and provide its implementation in the class that implements the particular interface. What is the purpose of creating an interface if we can create and implement methods in classes separately?
Plz help me I'm new in Java?
Consider an example :
Suppose you are creating some application which is concerned with the animal kingdom.
Now you are asked to create a dog, cat, lion etc objects.
So first thing will come to your mind, since these all belong to animal kingdom I can create a base class named ' Animal ', and everything will inherits it. Now yo created something like this
class Animal {
legs;
family;
eat();
roam();
sleep();
makeNoise();
}
So all the animals inheriting the animal class will have these features. You can call this as a "IS-A" relationship. Like Dog IS-A Animal.
Now suppose you are asked to use your animal simulation program for some science-fair. You can use this design in that too.
Now suppose someone asked you to use your simulator in a pet-shop.
Since you don't have any pet behavior. What you did is add the pet features in the base class and thought this will work.
So now you program can create a lion which has the pet behavior. STRANGE!!
Now what you need to put all the pet behavior in one place and make sure that all the pet animals should posses it.
A way to do is create another superclass with all pet features and extend it. This is multiple inheritance, which JAVA don't allow (just Google deadly diamond of death). So comes the interface.
Interface is more like a set of behaviors which your object implements.
And since every object can have its own set of implementations, all these methods should be abstract.
It gives you polymorphic benefits without deadly diamond of death problem. It is a more like a contract which defines that your object must implements following features.
So now what you can do
interface PetBehavior{
befriend();
play();
}
and classes from different inheritance tree can implement this interface.
We do that in order to organize data. This the ability to perform operations lots of times and to structure your data. There is another thing called Vector. If objects implement the same method, they can be iterated and sorted via this Vector
Because with a single interface you can have multiple implementation.
For example if you have a list interface, implementation could be ArrayList or LinkedList.
They have different performances and are used based on the context. By having the same interface, if you want to change something you have to simply change from this
List<String> arrayList = new ArrayList<String>();
to this
List<String> arrayList = new LinkedList<String>();
bacause they have the same methods but implemented in different ways
I used to have this question too!
There are 3 main reasons why we need interfaces:
it makes more sense. Interfaces create a "can be used as" or "have the ability to" relationship between the implementing class and the interface. For example, you can have an interface called Flyable and all the things that can fly implements this interface. E.g. Bird, airplane and balloons. These implementing classes "have the ability to fly" because they all have a fly method or whatever is defined in the interface. Also, if a method requires a Flyable object, the programmer can just pass in a bird, an airplane, etc. with his/her common sense. But still, this isn't very practical, just like whether you should write the { on a new line doesn't matter.
It makes it easier for you, and other programmers using your API or library or whatever you are creating, to create custom behaviors. Java Swing is a very good example. If you don't know what swing is, it is an API used to create programs that has a "window" or GUI. How are you going to tell the computer what to do when the user clicks on a button? Via an interface! There is an interface called ActionListener. It let you create your own things to do when the users clicks on a button. You just pass an ActionListener object to a method, with your own implementation, and it will be run when the button is clicked! If my words don't make sense, let me use one sentence to summarize all this.
interfaces provide a way to pass around different methods (with custom implementations) as parameters in methods.
EDIT
Oh I missed one point!
interfaces aid polymorphism. Say you have a dog, a cat, and a fish class and all of them don't implement any interfaces but have similar methods (move, sleep, eat etc). If you want to create an array of all your animals, you can only create an array of Object because all Java classes inherits Object. This is unsafe because then you can add whatever you want into the array, and you need to do casting in order to use those move sleep eat methods. So sad! :( If you create an interface called Animal which contain the three common methods and make all three classes implement it, you can just create an array of Animal. And you don't even need to cast it to the right type before you can access move sleep eat! How cool is that!
So remember to create interfaces when a lot of your classes have similar methods but different implementations to just UNITE THEM ALL!

What is the use of a sub class object being referred by a super class variable in java? [duplicate]

This question already has answers here:
Using superclass to initialise a subclass object java [duplicate]
(5 answers)
Closed 9 years ago.
Suppose B extends A and we have a declaration A a=new B(); What is the use of referencing sub class object by super class variable?And what are the fields and methods accessible by the object a((only child class methods and variables) Or (from both child and parent class))?
Thank u
The reason is abstraction. The idea is that you don't need to know every little tiny detail about the object. For example, say you're driving a car. For the most part, the pedal on the right makes you go faster, the pedal on the left slows you down, and the big round thing in front of you steers the car. How that happens isn't important for the driver (a.k.a. user) to know, but it is very important for those details to work properly in order for the car to actually move.
The use of using super class reference type is that you dont have to worry about implementation class (or specific class), like List a = new ArrayList();
only methods exposed by super class will be accessible in this case.
So this is mainly to achieve: Polymorphism as well as Abstraction.
The main principal is that client coding against a higher label interface and does not worry about the low level implementation.
This gives a flexibility to change the implementation without changing the clients. And also client has a flexibility to try multiple implementations.
In your example, the members that will be accessible from a are the ones defined by the A class.
Hi In simple words we can say that All B's are A's and not all A's are B's. That is how the whole inheritence works. It givces the required abstarction.

Conceptual Difference: Fully Abstract Class v. Interface

I am wondering if I have the correct understanding of the theoretical difference between a fully abstract class and an interface. I understand the technical differences.
My understanding is that classes are used for concrete objects and interfaces for features those objects can exhibit. So If I was making a car class, and I wanted that car to have a navigation feature, I would make a navigation interface rather than an abstract class correct? (Replace with any feature, i.e. automatic parking, etc)
You are correct.
A boat or a plane could also have an automatic parking feature or a navigation system.
But in most models, something is either a boat or a car (let's leave flying cars out...).
Practically, in Java an abstract class is a good way to force an extension in a particular (unique) category. If you have AbstractPlane and AbstractBoat, you are sure an object is either one or the other.
The theoretical difference between the two is off-topic here, you might want to ask at http://programmers.stackexchange.com.
The closest on-topic question for so is what you can do with them, which you probably already know -- a class can implement two interfaces, it can extend only one class.
Fully abstract class is very similar to interface, practically identical. When it comes to particular languages, differences arises. For example, in Java class can extend only one other class but can implement many interfaces.
Regarding your example is correct. Class is collection of 2 main things: data and methods to work with that data.
Yes, you are on the right track. Think of it this way. You have a fruit. But you don't know which one it might be. So you make an interface fruit which is upto the user now how may they use this interface. It might be apple, oranges or peach. The interface fruit will have a definite size, color and environment it grows. Though this information changes according to different types of fruits.
In other words, interface is like a skeleton of something very very specific that you are trying to accomplish in the long run.

Use of Java [Interfaces / Abstract classes] [duplicate]

This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 9 years ago.
Lately i decided to take a look at Java so i am still pretty new to it and also to the approach of OO programming, so i wanted to get some things straight before learning more, (i guess it's never to soon to start with good practices).
I am programming a little 2D game for now but i think my question applies to any non trivial project. For the simplicity I'll provide examples from my game.
I have different kinds of zombies, but they all have the same attributes (x, y, health, attack etc) so i wrote an interface Zombie which i implement by WalkingZombie, RunningZombie TeleportingZombie etc. Is this the best thing to do? Am i better of with an abstract class? Or with a super class? (I am not planning to partially implement functions - therefor my choice for an interface instead of an abstract class)
I have one class describing the main character (Survivor) and since it is pretty big i wanted to write an interface with the different functions, so that i can easily see and share the structure of it. Is it good practice? Or is it simply a waste of space and time?
I hope this question will not be rated as subjective because i thought that experienced programmers won't disagree about this kind of topic since the use of interfaces / super classes / abstract classes follows logical rules and is thereby not simply a personal choice.
You can think of an interface as a "contract". You are defining a set of methods that classes which implement this interface must implement.
An abstract class, on the other hand, is used when you have some code that could be common to all the child classes you want to implement. So you might have an abstract class called Shape that has some common code, and in your derived classes (Circle, Square, etc.) you could have the code that is specific to those shapes (getArea would be an example). But something like color might be common to all shapes, so you could put a getColor method in your Shape abstract class.
And you can combine the two ideas. You can have abstract classes which implement interfaces, and this gives you the best of both worlds.
These concepts are used over and over again in OO, so it's important to understand them. You seem to be well on your way :).
So if your zombie class has some common behavior that applies to all types of zombies, it sounds like a good candidate to be an abstract class. You could also consider creating an interface (maybe a GameCharacter interface) if you have other characters in your game (maybe UndeadMice or something :)). Then your Zombie abstract class and UndeadMouse abstract class would implement the GameCharacter interface.
When in doubt, I choose to follow the GOF paradigm.
Encapsulate what varies: - Define unique behavior in its own class. To refer the above example, implement behaviors for walking, running and teleportation in its separate class. This way, polymorphic behavior is implemented.
Conversely, **Aggregate what is common** - Use Abstract classes to define common behavior in polymorphic associations. I use these principles when designing relationships between objects.
Yes, I think you're heading down the right track with interfaces over abstract classes.
Any concrete Zombie you might want to make could possess any combination of the Walking, Running or Teleporting features you care to implement.
I think modern programming theory discourages inheritance as much as possible, because it inhibits reusability and flexibility in the long-run. Rather, use interfaces and composition to achieve flexibility without 'tight coupling'.
One methodology to re-use code without inheritance, you could apply the 'Favour composition over inheritance' paradigm.
I like to think Josh Bloch's 'Effective Java' (2nd edition) can be taken as "current thinking" ...
http://books.google.com/books?id=ZZOiqZQIbRMC&pg=RA1-PA71&lpg=RA1-PA71&dq=%22Bloch%22+%22Effective+java:+programming+language+guide%22+&hl=de&sig=RxlDlRBWUvNAzsAFzqOcftrYI5E#v=onepage&q&f=false
So, you could implement all your behaviours as independent classes, and then give each zombie implementation its own combination of behaviours, through implementation & composition..
Hope that makes sense & helps ...
I would have written Zombie as an abstract class to avoid the redefinition of the fields x, y, health, etc...
For the Survivor class, I would simply have declare public the functions to be used externally. I declare public functions at the top of the class. Declaring an interface when there is only one class implementing it uselessly adds a file to maintain. Avoid it.
Nobody agrees about the use of interfaces over super/abstract classes ;)
The main reason to use interfaces and super/abstract classes is to enable polymorphism. In your case for instance, you have stuff moving on the screen (the player and the zombies and so on). Why not make them all move on the screen using the same method? Maybe inherit everything that's going to move on the screen from an object called "Movable" or something like that.
And if you're really into this stuff you might want to look at mixins as well. It's not something that Java supports directly but there are libraries built for it.
I have different kinds of zombies, but they all have the same attributes (x, y, health,
attack etc) so i wrote an interface Zombie which i implement by WalkingZombie,
RunningZombie TeleportingZombie etc. Is this the best thing to do? Am i better of with an
abstract class? Or with a super class?
an abstract class will be a super class for your zombies. an interface would also in some sense be a super class (super interface?) for your zombies.
the common properties suggest at least an abstract base class for common properties.
(I am not planning to partially implement functions - therefor my choice for an interface
instead of an abstract class)
not sure what you mean by this.
if you had different kinds of monsters (goblins, orcs, etc.) you might find behaviour common to these that would want to belong to different base classes. this would suggest an interface.
i would start with an abstract base class and see what the code tells you as you write it.
I have one class describing the main character (Survivor) and since it is pretty big i
wanted to write an interface with the different functions, so that i can easily see and
share the structure of it. Is it good practice? Or is it simply a waste of space and
time?
your survivor is what is called a player-character (as opposed to a non-player character - someone in a game who will normally not attack your survivor).
most games treat all of these character types as some kind of monster since they will all have many properties in common (health. magic, treasures, weapons, etc.)
so perhaps that's more of an argument for an interface.
see:
Using inheritance and polymorphism to solve a common game problem
Class diagram examples for RPG (Role Playing Game)
designing class hierarchy for typical characters in role playing game
I don't think that in your case your interface and class structure aligns well with the reality. In fact, I believe (correct me if I'm wrong) that each zombie can be walking, running, teleporting etc. depending on where it is.
Therefore, you should have a zombie class or interface and have actions which modify the zombie's state. The action would probably be an interface or an abstract class, so that you can apply any action to a zombie without knowing what the exact action does (e.g. action.perform(zobie)).
If you have different kinds of zombies, such as three-legged-zombie and one-armed zombies, you might want to implement different classes which handle the zombie stuff, such as displaying themselfes or validating state changes (e.g. a special kind of zombie may not accept to be teleported).
in terms of your Zombie example, the interface will do well, unless you have common code that you want all zombies to do.
Say you have a Move method, that makes walkingzombies walk, runningzombies run, etc. However, if you want "Move" to make any kind of zombie do something common, then the interface is going to force you to duplicate code, as you cant put a body in an interface.
My opinion is you better use abstract class called Creature as a super class for all type of, well, creatures, and extend it to Zombie for all type of zombies.
And you will also need an interface.. to define what are the things that a creature can do..
like maybe, walk, or claw, or scream...
the reason why you need an abstract class is to disable the instantiation of Creature, you wouldn't want to have a creature without knowing what creature it is, right?

Categories