Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm learning java and was wondering in what situation you would want to extend a class like here is suggested:
http://5upcodes.blogspot.fi/2013/08/java-inheritance.html
Thanks!
My favorite example of inheritance is the shapes example. All squares are shapes, but not all shapes are squares.
Assume you have a class called "shape". All shapes have perimeter, area etc. These would be the data members of your shapes class.
lets say you wanted to create a class called circle. circle could extend your shape class, so that it would still have the data members of the shape class, and you could add elements that are specific to the circle, such as a radius. (a square wouldn't have a radius).
The circle class would be said to "inherit" from the shape class, because it has all of the features of a shape, and also new features specific only to the circle class.
When you want to create a class that is generally similar to the super class(the class being extended), you extend it and customize it. Overwriting some of it's functions, and/or add functions.
This is a "is-a" scenario, one of the three OOP pillars (inheritance, encapsulation, polymorphism). If you have a class Animal, then you may want to extend a Dog class from Animal. A dog is an animal, but not the other way around. All animals have cells, but dogs have other features aside from that. That'd be a pretty basic idea of it.
The OOP good practice is to program towards interfaces. But in some cases you can take advantage using inheritance: for example, when your top class has a well-defined behavior (i mean concrete code), which all the child classes will inherit - this reduces code, complexity and give you a better maintenance scenario.
In the other hand, if your model is too abstract (the basic behavior is not very clear), then you should think about using interfaces.
And if you're creating real-life software, don't forget design patterns - someone may already solved your problem.
For simple reason we extend one class two another and the funda is called as INHERITANCE.
Say,if you want to create a program in which there are two vehicle class i.e.- Car and Boat, which has similar properties except some.
public class Vehicle
{
void engine()
}
protected class Car extends Vehicle
{
void tyres()
}
protected class Boat extends Vehicle
{
void propeller()
}
You see both vehicle has engines but has different modes as one moves with the help of tyres and another with propeller.
So, two avoid re-writing code of method engine, we inherited it in sub-classes.
Hope, this will help ya !
Extending class is one of basics of OOP, along with interfaces. Lets say, you have general class called Building. It has members like area, city where building is (or coordinates) etc.
Now, with extend, you can specify house to "Cottage", "SkyScraper" etc. They will have functionality of parent + something more (eg. number of levels for SkyScaraper).
The primary reason to use inheritance is to extend behavior of the base class.
For instance, if you're making a video game you might have a Character class that contains all the code needed for a character to navigate the world and do whatever else they do.
You could then extend Character with Player and NPC, so that Player (representing the player character) contains the logic that allows the person playing the game to control their character, and NPC (representing a Non-Player-Character) contains the logic allowing the computer to control the other characters. This way, all of the logic core to every character is encapsulated in the Character class, and the subclasses only have the logic needed to extend specific behavior.
For example, the Character class might have a method for movement.
protected void MoveToLocation(x, y)
{
//movement logic goes here
}
And then the Player class might contain a mouselistener to move the player to wherever is clicked.
public void mouseClicked (MouseEvent mouseEvent)
{
MoveToLocation(mouseEvent.getX(), mouseEvent.getY());
}
And NPC will figure it out on its own somehow
protected void decideWhereToGo()
{
int destinationX, destinationY;
//logic for determining destination
MoveToLocation(destinationX, destinationY);
}
Because they both inherit from Character they both know how to MoveToLocation, and if you ever want to change how that is done you only have to modify the code in one place and every Character (whether they are a Player or NPC they are still a Character by way of inheritence) will have the updated behavior.
When you extend a class, you have a parent-child relation between the original one and the new, extending one.
The child class, the one extending the parent class, will have each and every member of the parent class, without the need to declare them again. Even the private members, though you won't be able to access them directly.
You extend a class when you want the new class to have all the same features of the original, and something more. The child class may then either add new functionalities, or override some funcionalities of the parent class.
You may also use extension when you want to have a set of classes that are related and share some common functionality, but with different implementation when it comes to the details. For example, usually for graphical interfaces you have a Control class, which has functionalities related to rendering and positioning. Then you have its children called Button, Textbox, Combo etc. All have some implementation in common, but each is different in their details.
Make sure to study about interfaces, too. Sometimes you want a lot of related classes so that they have a common set of members, but no shared functionality. In cases like that, it may be better to implement an interface than to extend a common class. An interface is like a class, but with no implementation in it (it serves only to tell you which members its implementors should have).
Generally extending a class is so that you are creating class based on something. For example, in order to create an activity, you must extend Activity. If your class is to setup a IntentService, then you must extend your class to use IntentService.
public class AClassNameHere extends Activity implements OnClickListener {
public class ClassName extends IntentService{
You can extend the superclass to Override super class method to be specific to sub class
example:
In case your superclass is a generic class with generic behaviour, eg Animal class can be a generic class like
class Animal{
private String name;
public String getVoice(){
return "Animal";
}
}
Now you need to create say a class Cat which is of Type Animal but with different voice then you just extend the superclass Animal and just override the getVoice() method
like
class Cat extends Animal{
public String getVoice(){
return "mew";
}
}
Now if you have code like this:
Animal cat= new Cat();
cat.getVoice();//it will return "mew"
Practically this you can use in number of situations like
1. Extending an existing framework class to your custom class.
2. If you are developing any framework you can expose some classes which you want the user to customize.
But overriding introduces IS-A relationship.
There are three major drawbacks with inheritance. Even though the relationship is an "is a" relationship, consider these three while deciding to inheriting a class.
Partial inheritance is not possible. You can't extend partially.
It is statically linked. Inheritance relationship is static. You can't change that relationship at runtime.
You can't restrict the behavior through inheritance. (That is possible in C++ through private inheritance. But not in java )
Almost never. It's best only to extend classes that have been actively designed for it. Most class implementors give no thought to what will happen if people extend their classes. There are all manner of issues.
Composition is your best friend.
Vulnerabilities include
you can no longer correctly implement equals() or hashCode() in subclasses
you are violating encapsulation, and now rely on the internals of another class
you are vulnerable to changes in the parent class
you are required to accept any new methods that get added to the parent class
you must worry about the Liskov Substitution Principle, which can lead to subtle bugs
Josh Bloch, in his excellent book Effective Java, 2nd Edition, talks about this in several places, including items 8, 16 and 17.
Related
I have a dilemma.
class A {
protected int x;
}
class B extends A {
private int y;
}
And I could use this hierarchy in my code, but I wonder if it is ok to just add new class to this hierarchy:
class C extends A {}
Class C is just there for type, so I could rename A to Base and have two classes inheriting from Base, but one is exactly the same as Base class.
What is better solution?
Class without implementation is sign of bad design, you need to create new class only when you have certain behavior that vary from parent to place to it. So in your case you don't need to create C, just rename A to Abstract, Base and make it abstract. In this way you have abstract class and implementation (A and B), in further development you may need to another implementation of type A and extends from it, only in this way you need to create class C.
The code is an abstraction describing the business problem you are solving. There is nothing stopping you from introducing an empty class if it makes sense in your business domain. The main goal is to make the code readable, to quote Steve McConnell:
Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’ Improve the code and then document it to make it even clearer.
However it would be discouraged if you would have to implement the same method twice in B and C. This would lead to code duplication.
This approach is usually used with interfaces in Marker Interface Pattern.
I'm self learning Java, and I'm stuck on a chapter about Interfaces. I simply cannot understand how they work in Java.
I believe I understand perfectly what Interface means and how they apply in everyday situations and technology.
But when it comes to Java, code-wise and logic-wise, I'm stuck. I don't get it. How does the concept work?
Say I have 3 objects, and 1 interface object. 2 Objects are ObjectCalculatingA, ObjectCalculatingB, ObjectMathFunctions, and ObjectInterface.
Supposedly in ObjectInterface there must be some sort of reference to the ObjectMathFunctions, so that ObjectCalculatingA and B can just access the math functions in ObjectMathFunctions without writting them all again in A and B.
Am I right?
An interface exists to facilitate polymorphism. It allows declaring a contract that any class that implements the interface must honor. And so it is a way to achieve abstraction and model complexity by looking for commonality between things.
An example? How about shapes? All shapes have an area, right? So you could have the following classes:
Square
Circle
Then let's say you have another class that allows you to collect shapes, and return the total area:
for (Shape shape in shapes)
{
area += shape.area() //This is polymorphism
}
In the example above, we don't care whether the shape is a square or a circle. We can accept either. We only care that it implements the Shape interface. Each object will provide their own custom implementation of area - these internal details aren't important, only that it honors the area contract . See now how we're managing complexity? We can use the class without having to worry about all of the things that go on inside. At this point what it does is important to us, not how it does it, which lets us focus on the problem at hand not getting distracted by complex details.
This polymorphism is one of the reasons why object oriented programming was considered such a powerful evolutionary step in programming. The other key foundation concepts in Object Oriented Programming are:
Encapsulation
Inheritance
. . . you'll also need to learn these.
Abstract Base Class vs Interface
As a comment said, another way to achieve polymorphism is to use an Abstract Base Class. Which should you choose?
Use an interface class implementing it will have its own hierarchy and dependencies. For example a media player. A Movie Player and a Sound Player might have totally different base classes, so use an interface.
Use an Abstract base class when you have some commonality between things, but the specifics vary. For example a message parsing framework.
In simple lay mans language. Interface is a contract and classes implementing the interface need to adhere to the contract. There can be many implementations for same interface and users can select which implementation they wish to use. For more detailed information I suggest you read book like HeadFirst JAVA.
Once you begin software development you will understand that many a times you would come across an already implemented piece of code which you feel is not properly implemented. But at the same time a colleague of yours feels its correctly implemented and serves his purpose. This is where interfaces come into play. Your colleague who feels this implementation works for him can continue using the current one whereas you can implement your new implementation but you need to make sure that it adheres to the interface so that in future if your implementation is better, your colleague will have an oion to switch over.
List<String> myList = new ArrayList<String>();
In above example arraylist is on of the implementations of the List interface. Consider this example, ArrayList is not suiting your requirments so you can do the following.
myList = new LinkedList<String>();
This is the power of 'Coding to interface'
From your example, it shows that you lack a basic understanding of Object-Oriented Programming. You are trying to learn how to run without having learned to stand up yet.
In your example, you assume there is a class ObjectMathFunctions. This is not Object-oriented at all, classes should model a real concept.
1. Learn about objects / classes
You should first learn how classes and objects work. A class is not just any arbitrary division of code, it models something real. Examples: Car, Wheel, etc.
2. Learn about inheritance
After you understand that, learn about inheritance: a Car has a getWeight() method. A Wheel has a getWeight() method as well. Hmm, maybe they are both subdivisions of a broader concept: PhysicalThings. Every PhysicalThing has a getWeight() method.
After this, learn about overriding methods in subclasses, learn about abstract classes, etc.
3. Learn about interfaces
Now you will understand that an interface is very similar to an abstract class. You will have done some exercises where you already encountered the problem "This is a PhysicalThing, but it is also CanExplode (e.g. wheel of car, dynamite, etc). This single inheritance model is annoying, how do I fix this?".
If you know that a class can consist of both data and the functions that operate on the data, then an interface is just a list of the functions that a class has to implement.
Take a light switch interface, ILightSwitch ...
public interface ILightSwitch {
void turnOn();
void turnOff();
}
A class implements an interface if it implements those functions above.
e.g. A LightSwitch class might be
public class LightSwitch implements ILightSwitch {
boolean on = false;
void turnOn() { on = true; }
void turnOff() { on = false; }
}
The LightSwitch class implements the ILightSwitch interface.
Since I am trying to learn more about OOP (Java) I'm working my way through some literature where I found this 'task'. Unfortunately I am having kind of a hard time since I am pretty new to OOP and I don't have any sample solution to this. Maybe some of you can give me some input so can work my way through this.
Define a class hierarchy for these classes:
quadrilateral
convex quadrilateral
trapezoid
parallelogram
rhombus
rectangle
square
Create an instance of each class if possible
Define reasonable attributes and methods in each class
Overload and override methods
Write reasonable constructors for each class
Use modifiers (abstract, static, final, public, protected and private) in a meaningful way
How could an interface be used for this task?
01 Class hierarchy
Okay, this is simple math and you can find tons of information on the hierarchy of quadrilaterals everywhere. Here is what I did:
Creating Objects of each class is no big deal, but I still have some problems with understanding all the OOP-techniques. There are some points where I don't know what would be the better way to do it... (e.g. the square which inherits from two classes, which in java is simply not possible). Also, formulas (like calculating the surface area) would be overwritten all the time anyhow (since they are different most of the time), so why would I need inheritance anyway? Couldn't I just use an interface, use it in all of those classes an force them to implement these formulas?
Greetings - Vulpecula
In real life, you probably would be better off using an interface. Deep inheritance structures like that are often frowned upon; it's generally considered good to 'prefer composition over inheritance' (http://en.wikipedia.org/wiki/Composition_over_inheritance). You might for instance have a 'quadrilateral' interface that defines 'surface area' and 'perimeter', and then have the other shapes satisfy that interface.
If this is a homework question however, then you should probably base the class hierarchy on whatever examples your textbook/teacher have provided previously. It's not about designing robust software, it's about proving to your teacher that you learned how to do things in whatever way they think you should do them.
An abstract class as the base of a moderately complicated hierarchy is not as flexible as an interface. A class--abstract or not--forces a specific type of implementation.
Without thinking too hard about it, here's one way to start:
public interface Quadrilateral {
int getTopMillimeters();
int getLeftMillimeters();
int getRightMillimeters();
int getBottomMillimeters();
}
From this raw data, you could also define
getTopLeftAngle(), getTopRightAngle(), ...
which would all compute their values based on the lengths.
I too would emphasize composition over inheritance. The end-effect can indeed be a complex inheritance structure.
For me, composition is heirarchy of "Composer" classes, which do NOT implement the interface. Such as
public class QuadrilateralComposer {
private final int iTopMM;
private final int iBtmMM;
...
public QuadrilateralComposer(int i_topMM, int i_bottomMM, ...) {
if(i_topMM < 1) {
throw new IllegalArgumentException...
}
if(i_bottomMM < 1) {
throw new IllegalArgumentException...
}
...
iTopMM = i_topMM;
iBtmMM = i_bottomMM;
...
}
public int getTopMillimeters() {
return iTopMM;
}
...
Which is then composed by an abstract class:
public class AbstractQuadrilateral implements Quadrilateral
private final QuadrilateralComposer qc;
public AbstractQuadrilateral(int i_topLen, int i_bottomLen, ...) {
gc = new QuadrilateralComposer(i_topLen, i_bottomLen, ...);
}
public int getTopLength() {
return gc.getTopLength();
}
...
Abstract classes never extend other abstract classes, they only use internal Composers (and actually implement the interface). On the other end, Composers only extend Composers, and use other composers internally.
(Three notes: Protected functions are in the Composer as public function_4prot() and are implemented as protected function(), which call the _4prot version. And sometimes the abstract class can indeed implement everything in the interface. In this case, it would be concrete [non-abstract] and be named "SimpleXYZ", instead of "AbstractXYZ". Finally, static utility functions reside in the Composer.)
If EVERY interface is designed in this way, then ANY class can easily implement ANY interface, regardless which class they must actually extend. If abstract classes extend other abstract classes, that is a lot more work for classes that need to implement the interface, but happen to--and have to--extend something else.
This is not what you asked, but learning this concept changed my code for the WAY better. Seeing it mentioned in the accepted answer made me think through all of it. I've actually been slowly drifting away from inheritance to composition over the past few years, and after reading Effective Java, it was the final nail in the inheritance coffin, as it were.
Okay, the plan now is that I am trying to resolve this without any interface first. So here's the map of inheritance:
I am ignoring the fact, that the square is not only a rectange but also a rhombus.
The abstract class (quadrilateral) will define (but not implement) methods for calculating 'surface area' and 'perimeter'. Overriding methods is easy since every shape has different formumals for calculation but I am not really sure where I could use the overloading feature.
One more thing: Using an interface, would this be the desired way?
In an interview it was asked to me to justify when to choose interface and when to choose abstract classes and in which conditions you will choose out of the two only one.. I have come up with my analysis for interface and that is...
Interface is best choice for Type declaration or defining contract
between multiple parties.
If multiple programmers are working in different modules of a project they still use each others API by defining interface and not waiting
for actual implementation to be ready.
This brings us a lot of flexibility and speed in terms of coding and
development. Use of Interface also ensures best practices like
"programming for interfaces than implementation" and results in more
flexible and maintainable code.
But I don't have strong reasons to justify the abstract classes, Please advise..!
Abstract classes are used to group a number of concrete classes under one entity.
For example, take the abstract class Animal.
Animal is not something concrete. it's a family of, well, animals. but they all share certain aspectes, for example, each has a speak() option (well, except fish and sort). but each one implements it differently. this way you can override just the methods which are not the same, for example sleep() or breath() are common (again, fish are differnet :) ).
Interfaces on the other hand are more direct definition of an 'action'. That's why most (if not all) the interfaces in Java ends with 'able' (Comprable, Serializable...)
By implementing the interface, you're telling other programmers or who ever uses your code that this class can do this and this.
A dog, for example, is not, Animable.
Basically, to sum it up, I think that the best definition is this.
Use abstract classes when you have a class that A is kind of B and interface when A can do B.
Hope that's help.
Abstract classes are used when you want to provide partial implementation.
Abstract classes can have default behaviour(implementation) if is required, interfaces cannot.
An abstract class can provide default behaviour for ALL methods or no methods whereas interfaces cannot.
Abstract classes can have state shared with all subclasses, interfaces don't specify state.
You can implement multiple interfaces, you can only extend one (abstract) class.
An interface declares a contract with whatever implements it. It's a guarantee that the class will contain the methods in the interface.
An abstract class is similar in that anything that subclasses it will also have to implement the abstract methods, but you can also have working methods with code in them.
I use interfaces a lot for callbacks with Android programming. Abstract classes I use a lot if I have a lot of similar data to display and just want small changes to implementation. Use an abstract class to cut down on repeated code while still having different implementation.
You are correct on your definition of interfaces.
Abstract classes should serve a completely different purpose. As an example, let's say you are implementing several classes for an animal simulator. 'Animal' defines several behaviours that could already have a basic implementation, but is not itself something that would make sense to have instantiated. Likewise for 'Mamal', a bubclass of 'Animal'. Only a subclass 'Tiger' would not be abstract, but most of what a tiger does that's not tiger specific would be implemented in it's abstract superclasses.
1. If speaking generally, An Abstract class will be needed when we need to force down some features on the Sub-Class from Super-Class, letting the Sub-Class to have the flexibility to add other functinality.
Eg:
Let Car be the Abstract Super-Class, which has 4 Tyres, 1 Steering ,etc...
Now the Sub classes like Santro i10, Maruti-800, Mahindr Bolero etc are Sub classes,
but they need to have 4 Tyres, 1 Steering to be called a car, not they can have a radio or not as an additional feature.
2. Interface was introduced in java, because there is no Multiple Inheritance.
3. Interface is more about providing a role.
Eg:
Let Dog be the Super-Class.
Wild Dogs and Pet Dogs are Sub-Classes.
Wild Behavior and Pet Behavior are Interfaces
Now as both Wild Dog and Pet Dog are dogs, but with different behavious. Then they must implement the Wild Behavior or Pet Behavior respectively
you'd want to use an abstract class when you want your classes to only implement the methods if the situation would call for them.
an example would be if you had a super class vehicle and you wanted your sub-classes to give you number of wheels if they have them. You wouldn't need them if they were boats so the contract would force you to implement still while you could just out right ignore it for your abstract class.
Assume, we have an abstract class A and we want to force all subclasses to have a certain field. This is not possible in Java, because we can not define abstract fields.
Workaround 1: Force subclasses to implement a method which delivers the wanted value.
abstract class A {
abstract int getA();
}
Drawback: Each subclass has to implement a method for each abstract field we want to have. This can lead to many method implementations.
Advantage: We can use the method getA in the abstract class and implement methods with it in A without implementing them in each subclass. But the value behind the method can not be overwritten by the abstract class.
Workaround 2: Simulate the abstract field by forcing the subclass to give the abstract class a value.
abstract class A {
int a;
public A(int a) {
this.a = a;
}
}
Drawback: When we have multiple fields (> 10), the super constructor call will look a bit ugly and confusing.
Advantage: We can use the field a in the abstract class and implement methods with it in A without implementing them in each subclass. Plus, the value a can be overwritten by the abstract class.
Question: Which workaround is the common way to reach the goal ? Maybe there is a better one than the above ones ?
The abstract method is probably the most object oriented.
If you have too many fields, you may want to regroup those in a POJO (if a new concept is appropriate).
I prefer the first one . i dont love to couple classes in fileds name , how they handle state and how they save it. the first one is more close to open/close principal
I recommend to avoid inheritance. inheritance is very frigle and hard to maintenance. remember effective java advice - prefer composition other inheritance
I think opt.1 is the cleaner by far. A few getters and setters is not a big deal, and I doubt that many use cases would have more than just a few abstract "fields".
About opt.2, you forget that constructors are not inherited, and thus would require all sub classes constructors to be implemented in a way that takes a into account.
Workaround 2 is very common because of 2 advantages:
1) the one you mentioned - the field does not belong to the subclass - it belongs to the parent and that is important because it was "demanded" by the parent and because the parent can use it
2) When sub-classing from the parent you are very aware of this field because when you implement the constructor you must pass it on. If I saw the first workaround I wouldn't know what to understand from it, in this way I understand that the parent class needs this field to work, so it must have a meaningful value.
note: if you have a class that has 10 fields that need to be initialized something is probably wrong in your design.
1. Actually its not about what one prefers but its about the flexibility, and the ability
to adapt changes.
2. Its always better to Encapsulate Behaviors that keeps changing, either into an Interface or Abstract class.
3. You 1st Workaround will be good in places where you need different implementation for the same Behavior in Different classes. Then at this place either an Interface or your 1st Workaround will be a good choice.
Eg:
Consider Painting as a Class with paint() Method.
Now
paint() method can have Stroking, gliding, shading etc styles of doing it.
Then its better to Encapsulate that method into an Abstract class or an Interface.
public interface Paint{
paintDoIt(String style);
}
4. Your 2nd Wordaround will be good in a place, where you want certain behaviors to be MUST implemented by the Subclass.
Eg:
Consider Car as an Abstract Class, Now to be car its very important that it must have
a Steering, 4 wheels, Engine, etc. So these features must be implemented.
where as other features like music system, LCD ,etc are optional and depends on the car type.