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.
Related
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?
How is loose coupling associated with interfaces when we are bound to create an implementation class regardless? The implementation class is forced to implement all those methods defined in the interface. I don't understand how this allows for lose coupling? I'm new to object oriented programming and software design so if you could shed some light on this topic it would super helpful. An example would totally be icing on the cake.
The key point is that an interface doesn't just allow you to write one class which implements it, it allows you to write several.
When you have code which interacts with a class by using an interface, that code is able to work together with any class which implements said interface, regardless of how it implements it. That allows you to feed different classes to the same code without having to modify it.
Please note that interfaces are not the only way to reach a loose coupling of components. Loose coupling just means that components are able to work together without assuming anything about the internal workings of each other. You do that because the more your components treat each other as black boxes, the easier it becomes to do changes at one component without affecting any others. Interfaces can be one tool to work towards this goal, but neither are they required, nor are they the only tool which is worth mentioning in this regard.
The implementing class is able to choose HOW to implement the functionality.
public interface PersonRepository {
Person getPerson(String name);
}
Could be implemented by reading through a CSV file or by querying a database. The object which needs the person does not care how the person is found or loaded just that it is.
Hence it is deemed to be loosely coupled.
If it was tightly coupled it would need to know how to construct a SQL query or read a CSV file.
the client code is coupled to the interface. it is not coupled to the implementation. you can change t he implementation without compiling the client code or the interface.
see http://en.wikipedia.org/wiki/Dependency_inversion_principle and http://en.wikipedia.org/wiki/Open/closed_principle
IMHO, interfaces dont solve the coupling problem you describe. They solve implementation coupling problem. As long as you use the interface you are unaware of the implementation you choose. But you are sill bound to that interface. And what you describe, call coupling remains. In order to reduce call coupling you had to use another approach, i.e. Command Pattern
Might below explanation can answer this :
Into class A we need to have Object of class B. If directly exposure of B into A is there means there is Tight coupling. ex: one can add more methods into B or anything.
Which means Behavior of A can be changed based on more exposure of B. But if B class is implementing any Interface and we are passing that ref of Interface into A. means whatever changes in B class further user A class is not bother because we use ref of Interface for accessing B and got only required access.
Ex :
class A {
public void add( B b){
// Implementation
}
}
class B{
}
this is Tight coupling. Because user can make any changes to class B which are directly exposed to class A and this defines Tight Coupling(Greater the exposure of depending Object , more Tight Coupling). To resolve this one refer :
Interface L{
}
class B implements L{}
class A{
public void add(L b){
// Implementation
}
}
Since we are passing the ref of Interface L, adding changes into Implementation of B will not make any difference to class A.
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.
I want to turn a class I made into an abstract class and get another class to extend it. This is because the class (particle) is leaning heavily on the class I want to make abstract (vector).
I am not sure how I will use all those objects I instantiated with the new keyword or if it will totally mess things up. I am willing to try it to learn something about using the abstract classes in my own example but if anyone can help me understand what I am doing that would be great!
if your new class depends on vector then rather than inheriting it try composition ...
so lets say u want to make ur own Queue then its not good idea to inherit from vector rather have a data member of type vector .
this has many advantage over inheritance . If u need to change the container to some other say set u do not have to worry about changing interface. You still will have some add and remove interface to your class. So client code will be independent of the container you are using to generate Queue.
Just on side notes : Consider using composition over inheritance. And look at some design patterns and try understanding when you need composition and when u can not avoid inheritance.
from wht I understand you are trying to convert class MyClass to abstract class AbstractMyClass
So, If you convert MyClass to an abstract class all the statements like
AbstractMyClass myClass=new AbstractMyClass();
will give you an error as you cannot make an instance of an AbstractMyClass.
Also, if the situation is
abstract class AbstractMyClass
{
}
class ConcreteMyClass extends AbstractMyClass
{
}
then do can do something like
AbstractMyClass abstractMyClass=new ConcreteMyClass();
or the usual
ConcreteMyClass concreteMyClass=new ConcreteMyCLass();
Inheritance : is a relation. More importantly the interface of base class and sub class should be same. Here u do not want client code to add new element using push_back()(for C++) but a mothod like add().So interface is different, a clear indication of wrong use of inheritance.Composition : has a and also "implemented in terms of". This is from Scott Mayer in effective C++. As with your case, u want implement a new DataStrucutre in terms of some thing. So composition is what you need. Now derived class does not need to have same interface. In general if you find interface to be same its more like inheritance and if not composition. There are tons of other advantage of compositon on inheritance. Just google or pick any good design book.
I have an abstract class. I want to extend the abstract class by another abstract class and then implement the extended abstract class. Is it possible .If yes, whether it's a good approach in point of view regarding OOPS?
I'm not sure about Java in particular, but it should be valid.
In terms of OOP, if it makes sense, then run with it. To use some old examples, you might have a Vehicle abstract class and then LandVehicle and FlyingVehicle abstract classes. As long as your example makes sense as an abstract class, then you should be fine.
Yes, it is possible, and I don't see a reason not to use it if you need it (disclaimer: but however there are many ways to misuse this, and to over-complicate things, as with everything in programming usually).
One thing to notice is that the second abstract class doesn't need to implement abstract methods from first class, but the first concrete must implement both.
Yes, you can! One abstract class can be extended by another abstract class
Yes!
But it makes sense only if the abstract subclass adds more functionality (abstract or not).
Otherwise, I don't see the point.
Yes you can do it. And it is good practice if your child class adds more functionality. It allows to move toward specification. Your parent class becomes a more general class and child class a more specific one. And you can implement both as per your requirement.