I have an abstract super class with 40 attributes. I also have 2 subclasses that basically extend the super class. Now I want to convert one child class with another.
public abstract class ParentClass{
// ... many attributes
}
public ChildClassA extends ParentClass{}
public ChildClassB extends ParentClass{}
A simple class cast like this is not working and throws ClassCastException:
public ChildClassA to(){
return (ChildClassA) ((ParentClass) this);
}
I could manually write a copy constructor but its tedious work.
Another approach is to serialize and convert. For example using XML or JSON. But that is used for cloning a class and again deserializing would throw class cast exception.
Is there are any other better ways?
EDIT:
Since people have asked for design decision:
I have 2 tables of identical columns. One table has data and the other one doesn't. I have to retrieve rows from original table -> do processing -> put back in second table.
So to minimize code complexity I have super class entity (JPA) which has all the fields (more than 40 fields, annotated with`) and have 2 subclasses extending from it (because I can only have 1 #Table annotation per class).
Now to do processing I need to retrieve data from original table to original sub class. Create a new second subclass and copy values from original to new. Do processing. Persist 2nd entity onto 2nd table.
I would question the design decision of extending the base class with subclasses that don't add anything, especially since they have to be converted from one to another. You could use one class instead, but add an enum field that differentiates the types from one another. Then the conversion would be simply changing this field to a different value.
However, if you really need them to be different classes and be able to convert from one to another, and you don't want to write tedious code to copy fields manually, you could look up some Java mapping frameworks, like MapStruct.
A simple class cast like this is not working and throws ClassCastException
Sure, that an expected behavior. It's not possible to type cast between two classes like ChildClassA and ChildClassB that are not bound with IS-A relationship, they are siblings, they don't extend each other, and therefore they are not compatible.
I have an abstract super class with 40 attributes.
If the number of properties is unmanageable, that's clearly a code smell. I suspect that some of these 40 properties can be "folded" into several objects, which will make sense in your domain model.
I could manually write a copy constructor but its tedious work.
Since you have 40 properties, I guess primarily concern is to bring the code to the state when you can more easily maintain it rather than amount of typing. And I've given you advice on that point.
And as a tool for conversion, I would rather declare a method like toChildClassB() because it would be more expressive than a constructor call new ChildClassB(childA).
I am currently studying OOP and UML together, there is confusion regarding the use of association class or just the plain association. Let say a Company hires Person, as far as I know there are two ways to associate them, the first way is just a regular type of association(I think this is aggregation) like this.
Regular association
The second way is to use an associative class, kind of like the one the ER diagram, but the Company class no longer has the responsibility to hire any Person.
My questions are:
Which one is correct? (It seems like the second one makes more sense, but the first one isn't wrong either)
If the first way is not wrong, but then wouldn't Company knows too much about Person?
In what situations do I consider using association class over regular association?
Your association is not an aggregation, an aggregation has an empty diamond (<>), so it is a simple association.
None of the association ends has a name even when navigable, so why are you using an association rather than may be a dependency if you do not want property ? Of course if it is not an association you cannot have an association-class.
In the class Company we can see the attribute Employees, are you sure you do not want :
or
You named the association as the operation (hire), of course you can but an association just represent a semantic relationship, so hire does not represent the operation.
As rightly said by #Axel Scheithauer in his answer in case of an association-class the name of the class and the name of the association are common properties and must not be duplicated so cannot be different, from formal/2017-12-05 § 11.5.3.2 Association Classes page 200 :
Both Association and Class are Classifiers and hence have a set of common properties, like being able to have Features,
having a name, etc. These properties are multiply inherited from the same construct (Classifier), and are not duplicated.
Therefore, an AssociationClass has only one name, and has the set of Features that are defined for Classes and
Associations.
About to use an association or an association-class it is a choice.
If you want to know the date the company hired an employee and the employee salary (when hired / current) for sure an association-class is a good choice clearly showing what you want.
But you can also have Onboarding as a third class out of an association class and having association between the 3 classes :
and you can also have date and salary as attributes of Person supposing a person is necessary an employee :
else you can have the class Employee inheriting Person and having these additional attributes :
You have Java and C# as tag, none of these language support association-class, so even you use an association-class in UML when implementing it in Java / C# you will probably use one of the two other solutions.
Because there is no bidirectional navigability a company knows his employees but an employee does not know the company or companies where he/her works, do you really want that ?
I agree with everything that bruno said in his answer. However, I would add a third possibility: a simple Class.
If the relationship between two classes has properties, you have two options: An association class or a simple class associated with the two classes. The only advantage of taking an association class is, that you then can specify, that each pair of instances of the two associated classes can only be linked once. That means, each person can only work once for the same company. This is not quite realistic. In order to allow multiple links, you would need to specify {non unique} for the association ends of the association class ({unique} is the default). So, only in the {unique} case an association class adds semantics. If that's not needed I would avoid it.
One additional note: The association class is one element, but it is shown twice in a diagram, once as a rectangle and a second time as a line. Since they denote the same element, the name must be the same.
what is the difference between use and realization interface relationships? How to implement them into code (e.g. java)? (Maybe better explanation of my question: I have one interface, say I and two classes, say A and B. Class A realizes I and class B uses I. What is difference between these relationships and how it should be implemented?) ... I have found many definitions but still I dont see difference.
Thank you very much
A the "realize" relationship is implemented in Java with:
class A implements I {
...
}
The "use" can be many things: it just says that class B uses interface I in one way or another. Examples:
class B {
I aField;
...
void doSomethingWith(I obj) { ... }
I createAnI() { ... }
...
}
As Maurice Perry said about Realize is correct.
To additional explain about Use Relationship in UML, it is a type of Dependency relationship. see here
A Use dependency relationship indicates that the consumer class does one of the following things:
Temporarily uses a supplier class that has global scope,
Temporarily uses a supplier class as a parameter for one of its operations,
Temporarily uses a supplier class as a local variable for one of its operations,
Sends a message to a supplier class.
see IBM Documents here
I have been trying to implement a shadow variable so that one of my problem facts can keep track of which planning entity is relevant to it, the end goal being to simplify/speed up my rules.
I am looking at the optaplanner doc about shadow variables, particularly the cloudBalancing example. In the "normal" cloudBalancing, the class CloudComputer is not a planningEntity. But in the example below, it is annotated as a planningEntity.
Are we to understand that the class "hosting" the shadow variable should be a planning entity? I thought a planningEntity had to have a planningVariable, but CloudComputer does not. If the answer is yes, I suggest being more explicit about it in the documentation. If the answer is no, then there is a mistake in this example (the #PlanningEntity annotation should be removed from CloudComputer).
The following example is from the doc:
For a non-chained planning variable, the bi-directional relationship must be a many to one relationship. To map a bi-directional relationship between two planning variables, annotate the master side (which is the genuine side) as a normal planning variable:
#PlanningEntity
public class CloudProcess {
#PlanningVariable(...)
public CloudComputer getComputer() {
return computer;
}
public void setComputer(CloudComputer computer) {...}
}
And:
#PlanningEntity
public class CloudComputer {
#InverseRelationShadowVariable(sourceVariableName = "computer")
public List<CloudProcess> getProcessList() {
return processList;
}
}
Also, is this really all that is needed so that processList is kept up to date even when CloudProcess is cloned during solving?
There are 2 kinds of planning variables: genuine (#PlanningVariable) and shadow variables. Any class that has either or combination thereof needs to be annotated as a #PlanningEntity (and added to the solver config unless you're using scanAnnotatedClasses).
Yes, this is because of the planning cloning. With the shadow variable, CloudComputer doesn't change during the planning so it doesn't need to be planning cloned. With the shadow variable, it changes during planning, so it needs to be cloned. If it wouldn't be planning cloned, the best solution would get corrupted when the internal working solution changes. That in turn would affect score calculation (if it uses the inverse list) and any consumer of best solution events or the best solution result returned by solve().
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.