Java generics problem - java

I'm working on a project where I am trying to use generics but I'm having a hard time.
Say I have a many cars, all of them implemented in a different class (eg. audi.java, toyota.java, etc..) and each of them have a method called startCar(). Now I want to create a class Cars that lets other classes use these cars. However the following will not work. How should I go about implementing it?
public class Cars {
private MyCar mycar;
private class MyCar <MySpecificBrandOfCar>{
private MySpeicifBrand mySpecifcCar;
public MyCar(){}
}
public Cars(){
myCar = new myCar<audi>;
}
..other methods..
}
I also tried creating an interface, but that gave errors too.
Thanks
EDIT, attempted nfechner's suggestion
Thanks for all the responses!
Would the following work (NB:GenericCar is an interface that is implemented by all cars (eg. audi.java) and has functions such as startCar()
public class Car{
private GenericCar mycar;
public Car(){
mycar = new audi();
}
}

Generics can't be used to instantiate a class unfortunately, not in Java. Perhaps you could be a bit more specific about your intention, but you might find it useful to have some base class Car and have each specific car extend it. If you define the startCar() method in the base class Car, every subtype of Car will also have this method through polymorphism.
public class Car{
public void startCar(){ }
}
public class Audi extends Car{}
public class Toyota extends Car{}
and so on.

Your code looks a bit overengineered. What's wrong with a simple Car interface, that all car types implement?

In this example Inheritance and Polymorphism will be a better solution than Generics.
Check this example. Java Tutorial - Inheritance and Polymorphism

You should not use generics here. (Think of them as type-parameters you do not want to fix, e.g. as for Collection).
If cars of different brands do behave differently, do inheritance instead, like Jonathan suggests.
But a better design is using composition instead of inheritance, i.e. Cars have a field of the class Brand. This is especially the case if the behavior is not strongly influenced. And I don't think an Audi behaves that much different from a Toyota.
Furthermore, I don't think there are that many brands, and you probably only need one instance of each brand. So use an enum instead of a class for Brand. In detail:
public class Car {
public static enum Brand { Audi, Toyota };
private Brand brand;
public Cars(Brand brandParam){
this.brand = brandParam;
}
//..other methods, getter and setter for brand
}
You can put methods in the Brand enum for the small and specific varying behavior. I think Josh Bloch, the author of Java Enums, explains their capabilities very well in Effective Java, 2nd edition.
Finally, try to choose better names for your classes and variables (I don't think MyCar is telling you anything).

This is not a circumstance where using generics is appropriate. You should use an interface or a superclass. I'm not sure what errors you were seeing with an interface, but it would be easier to fix them than to try to fix your problems with this approach.

Related

Is there a better way to create an abstract class that extends another abstract class and adds new features?

I have an abstract class that has a concrete method solveand several abstract methods that are used by solve:
public abstract class A{
public void solve(){
//code for solve
}
public abstract void a();
public abstract void b();
}
Then I have another class B that extends A, reimplements the solve methods using the abstract methods from A and new ones added (c,d). It also has a boolean field that indicates if it has to use the solve A or the one from B.
public abstract class B extends A{
boolean useA;
public B(boolean useA){
this.useA = useA
}
public void solve(){
if(useA) super.solve();
else // code for solve
}
public abstract void c();
public abstract void d();
}
Then I have a concrete class C that extends B, implements all methods and has a boolean to indicate if solve has to be used or not.
public class C extends B{
public C(boolean useA){
super(useA);
}
... //code for a,b,c and d
}
Is there any way to do this better? I think that maybe it's not following the principles of OOP.
Some already mentioned the decorator pattern, and there is the strategy pattern too.
However one might use lambdas for injecting some handlers.
Handlers might be done using public service / protected requirement:
class A {
public final f() {
...
onF(x, y);
}
protected abstract void onF(X x, Y y);
}
Solution complexes often are better of without inheritance, but as field, delegating to a field.
In that the answer of #LonelyNeuron gives good arguments.
In short: when in doubt, code it out first, and refactor it to some elegant model. Separating concerns and such.
The problem is, that the best solution for OOP is sometimes heavily over-engineered. So in some cases the solution which takes the least amount of work will be the best.
Also it is really hard to judge in this case. While it is good that you tried to create a Minimal, Complete, and Verifiable example, it lacks the most important information about what should inherit what: the purpose of each class. You could for example imagine that it might make sense to split your class B into two, where one does and the other doesn't override solve(), but if that is a good idea can only be decided to ask the right questions about the purpose of each class.
I suspect that you are asking these questions because you want to know the best way to reuse code in your classes. If that is the case: don't. Taken from this wikipedia article:
In most quarters, class inheritance for the sole purpose of code reuse has fallen out of favor. The primary concern is that implementation inheritance does not provide any assurance of polymorphic substitutability—an instance of the reusing class cannot necessarily be substituted for an instance of the inherited class. An alternative technique, explicit delegation, requires more programming effort, but avoids the substitutability issue. In C++ private inheritance can be used as a form of implementation inheritance without substitutability. Whereas public inheritance represents an "is-a" relationship and delegation represents a "has-a" relationship, private (and protected) inheritance can be thought of as an "is implemented in terms of" relationship.

How can a child interface reuse its parents' implementations?

Recently I had an interview and I was asked the following question. Given the following class/interface structure:
Question:
How can one implement interface EmployedStudent to reuse code from StudentImpl and EmployeeImpl.
I suggested to compose Employee and Student into my implementation.
Based on the interviewer's reaction I don't think they found it to be the best solution. I spent a lot of time thinking about it but I cannot come up with another solution.
Create a class that implements both Employee and Student. In your class, create an instance of both EmployeeImpl and StudentImpl. Make your class delegate all method calls to either one of the objects then.
public class EmployedStudent implements Employee, Student {
private EmployeeImpl employee = new EmployeeImpl();
private StudentImpl student = new StudentImpl();
public int getSalary() {
return this.employee.getSalary();
}
public float getAverageGrade() {
return this.student.getAverageGrade();
}
}
So, you could have implements Employee, Student internally delegating to both EmployeeImpl and StudentImpl, but also inherit from one implementation class.
Now the class name EmployedStudent (not StudyingEmployee or BothEmployeeAndStudent) suggests:
class EmployedStudent extends StudentImpl implements Employee {
Employee asEmployee = new EmployeeImpl();
Yeah, a tiny bit more efficient as only delegating to one other class.
The use-case is however far from realistic: all kind of combinations are thinkable of several classes. In that case your solution is more universal. Really universal, is a lookup-mechanism:
public class Person {
public <T> T as(Class<T> klazz) { ... }
}
Person person = ...;
Student asStudent = person.as(Student.class);
if (asStudent != null) {
...
}
Employee asEmployee = person.as(Employee.class);
if (asEmployee != null) {
asEmployee.quitJob();
asEmployee = person.as(Employee.class); // null
}
That is a lookup of capabilities. It typically can replace a cumbersome inheritance hierarchy, say of Vehicle, RoadVehicle, SwimmingVehicle (boat), FlyingVehicle (air plane), WaterAirplane (?), AmphibianTank (?) by using capabilities Swimming, Flying, Driving.
The difference is the entire decoupling.
As java doesn't support multiple inheritance, you could/should
either have a field for each of the wanted superclasses
or derive from one superclass and have a field for the other one.
The fields are then referred to by "our" implementation of the respective methods.
This is one of the design patterns from the GoF, I think it is the Proxy pattern.
With Java 8, you can move code into the interface itself. That solves the "multiple inheritance" problem.
While the Interface Segregation Principle can sometimes be helpful, and some people scoff at the idea of interfaces which don't promise that all implementations will support all members, I would suggest that it may be helpful to have Student and Employee interfaces which include isStudent and isEmployee members, and then have Person implement both interfaces; some methods like giveRaise() shouldn't work on someone who isn't an employee, but others like getOutstandingPay() should work just fine (if someone hasn't earned any money, the method should simply return zero).
While it may seem ugly to complicate all Person objects with methods that won't be applicable for many of them, such a design avoids difficulties in the event that a student gets hired, or an employee starts taking classes. Having separate classes for Student, Employee, and StudentEmployee, even if one could do so easily, would require that a Student who got a job be replaced with a new object instance in order to become a StudentEmployee. By contrast, if one has a Person class whose instances may or may not be able to handle methods like giveRaise, then one can handle situations where objects' abilities change during their lifetimes.

Interface method referencing a concrete class as parameter causes coupling?

I was thinking about programming to interfaces and not to concrete classes, but I had a doubt: should any interface method be able to hold references to concrete classes?
Suppose the following scenarios:
1)
public interface AbsType1 {
public boolean method1(int a); // it's ok, only primitive types here
}
2)
public interface AbsType2 {
public boolean method2(MyClass a); // I think I have some coupling here
}
Should I choose a different design here in order to avoid the latter? e.g.
public interface MyInterface {} // yes, this is empty
public classe MyClass implements MyInterface {
// basically identical to the previous "MyClass"
}
public interface AbsType2 {
public boolean method2(MyInterface a); // this is better (as long as the
// interface is really stable)
}
But there's still something that doesn't convince me... I feel uncomfortable with declaring an empty interface, though I saw someone else doing so.
Maybe and Abstract Class would work better here?
I am a little bit confused.
EDIT:
Ok, I'll try to be more specific by making an example. Let's say I'm desining a ShopCart and I want of course to add items to the cart:
public interface ShopCart {
public void addArticle(Article a);
}
Now, if Article were a concrete class, what if its implementation changes over time? This is why I could think of making it an Interface, but then again, it's probably not suitable at least at a semantic level because interfaces should specify behaviours and an Article has none (or almost none... I guess it's a sort of entity class).
So, probably I'm ending up right now to the conclusion that making Article an abstract class in this case would be the best thing... what do you think about it?
I would use interfaces because composition is much better than inheritance. "Should any interface method be able to hold references to concrete classes ?", why it shouldn't? Some classes within package are coupled, it's a fact and common use technique. When you marked this relation in interface then you see on which classes is dependent your implementation. Dependency or composition relations are not inheritance so a i would avoid abstract class.
In my opinion Interfaces are fine for all types where the implementation may vary. But if you define a module which introduces a new type, that isn't intended to have alternative implementations then there is no need to define it as an Interface in the first place. Often this would be over-design in my opinion. It depends on the problem domain and often on the way how support testing or AOP-weaving.
For example consider a 2D problem domain where you need to model a Location as a type. If it is clear that a Location is always represented by a x and y coordinate, you may provide it as a Class. But if you do not know which properties a Location could have (GPS data, x, y, z coordinates, etc.) but you rely on some behavior like distance(), you should model it as an Interface instead.
If there are no public methods which AbsType would access in MyClass then the empty interface is probably not a good way to go.
There is no interface declaration (contract) for static methods, which otherwise might make sense here.
So, if AbsType is not going to use any methods from MyClass/MyInterface, then I assume it's basically only storing the class object for some other purpose. In this case, consider using generics to make clear how you want AbsType to be used without coupling closely to the client's code, like
public class AbsType3<C extends Class<?>> {
public boolean method3(T classType) {...}
}
Then you can restrict the types of classes to allow if needed by exchanging the <C extends Class<?>> type parameter for something else which may also be an interface, like
<C extends Class<Collection<?>>>.
Empty interfaces are somewhat like boolean flags for classes: Either a class implements the interface (true) or it doesn't (false). If at all, these marker interfaces should be used to convey an significant statement about how a class is meant to be (or not to be) used, see Serializable for example.

Difference between Inheritance and Composition

Are Composition and Inheritance the same?
If I want to implement the composition pattern, how can I do that in Java?
They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".
You do composition by having an instance of another class C as a field of your class, instead of extending C. A good example where composition would've been a lot better than inheritance is java.util.Stack, which currently extends java.util.Vector. This is now considered a blunder. A stack "is-NOT-a" vector; you should not be allowed to insert and remove elements arbitrarily. It should've been composition instead.
Unfortunately it's too late to rectify this design mistake, since changing the inheritance hierarchy now would break compatibility with existing code. Had Stack used composition instead of inheritance, it can always be modified to use another data structure without violating the API.
I highly recommend Josh Bloch's book Effective Java 2nd Edition
Item 16: Favor composition over inheritance
Item 17: Design and document for inheritance or else prohibit it
Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.
See also:
Composition versus Inheritance: A Comparative Look at Two Fundamental Ways to Relate Classes
Composition means HAS A
Inheritance means IS A
Example: Car has a Engine and Car is a Automobile
In programming this is represented as:
class Engine {} // The Engine class.
class Automobile {} // Automobile class which is parent to Car class.
class Car extends Automobile { // Car is an Automobile, so Car class extends Automobile class.
private Engine engine; // Car has an Engine so, Car class has an instance of Engine class as its member.
}
How inheritance can be dangerous ?
Lets take an example
public class X{
public void do(){
}
}
Public Class Y extends X{
public void work(){
do();
}
}
1) As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature
public int work(){
}
Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be very dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in superclass all the time. So we need to avoid this strong and unnecessary coupling.
How does composition solves this issue?
Lets see by revising the same example
public class X{
public void do(){
}
}
Public Class Y{
X x = new X();
public void work(){
x.do();
}
}
Here we are creating reference of X class in Y class and invoking method of X class by creating an instance of X class.
Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.
2) Second very good advantage of composition in that It provides method calling flexibility, for example :
class X implements R
{}
class Y implements R
{}
public class Test{
R r;
}
In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance
3) Another great advantage : Unit testing
public class X {
public void do(){
}
}
Public Class Y {
X x = new X();
public void work(){
x.do();
}
}
In above example, if state of x instance is not known, it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance as you were heavily dependent on superclass to get the state of instance and execute any method.
4) Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.
Lets take an example to understand this :
Public class Transaction {
Banking b;
public static void main(String a[])
{
b = new Deposit();
if(b.deposit()){
b = new Credit();
c.credit();
}
}
}
Good to know :
composition is easily achieved at runtime while inheritance provides its features at compile time
composition is also know as HAS-A relation and inheritance is also known as IS-A relation
So make it a habit of always preferring composition over inheritance for various above reasons.
The answer given by #Michael Rodrigues is not correct (I apologize; I'm not able to comment directly), and could lead to some confusion.
Interface implementation is a form of inheritance... when you implement an interface, you're not only inheriting all the constants, you are committing your object to be of the type specified by the interface; it's still an "is-a" relationship. If a car implements Fillable, the car "is-a" Fillable, and can be used in your code wherever you would use a Fillable.
Composition is fundamentally different from inheritance. When you use composition, you are (as the other answers note) making a "has-a" relationship between two objects, as opposed to the "is-a" relationship that you make when you use inheritance.
So, from the car examples in the other questions, if I wanted to say that a car "has-a" gas tank, I would use composition, as follows:
public class Car {
private GasTank myCarsGasTank;
}
Hopefully that clears up any misunderstanding.
Inheritance brings out IS-A relation. Composition brings out HAS-A relation.
Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.Classic example being of a duck class which implements a flying behaviour.
public interface Flyable{
public void fly();
}
public class Duck {
Flyable fly;
public Duck(){
fly = new BackwardFlying();
}
}
Thus we can have multiple classes which implement flying
eg:
public class BackwardFlying implements Flyable{
public void fly(){
Systemout.println("Flies backward ");
}
}
public class FastFlying implements Flyable{
public void fly(){
Systemout.println("Flies 100 miles/sec");
}
}
Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.
Composition is just as it sounds - you create an object by plugging in parts.
EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car example above,
Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel
So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House protects its occupants, and how a Car protects its occupants.
Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.
For example, MotorVehicle may come with a Fuelable method and Drive method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive method because the Motorbike drives very differently to a Car.
With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).
Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,
iFuelable Interface:
void AddSomeFuel()
void UseSomeFuel()
int percentageFull()
then you can have a method somewhere else
private void FillHerUp(iFuelable : objectToFill) {
Do while (objectToFill.percentageFull() <= 100) {
objectToFill.AddSomeFuel();
}
Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel, it can be filled. End of story.
If you used Inheritance instead, you would need different FillHerUp methods to deal with MotorVehicles and Barbecues, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.
Are Composition and Inheritance the same?
They are not same.
Composition : It enables a group of objects have to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies
Inheritance: A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.
If I want to implement the composition pattern, how can I do that in Java?
Wikipedia article is good enough to implement composite pattern in java.
Key Participants:
Component:
Is the abstraction for all components, including composite ones
Declares the interface for objects in the composition
Leaf:
Represents leaf objects in the composition
Implements all Component methods
Composite:
Represents a composite Component (component having children)
Implements methods to manipulate children
Implements all Component methods, generally by delegating them to its children
Code example to understand Composite pattern:
import java.util.List;
import java.util.ArrayList;
interface Part{
public double getPrice();
public String getName();
}
class Engine implements Part{
String name;
double price;
public Engine(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Trunk implements Part{
String name;
double price;
public Trunk(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Body implements Part{
String name;
double price;
public Body(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Car implements Part{
List<Part> parts;
String name;
public Car(String name){
this.name = name;
parts = new ArrayList<Part>();
}
public void addPart(Part part){
parts.add(part);
}
public String getName(){
return name;
}
public String getPartNames(){
StringBuilder sb = new StringBuilder();
for ( Part part: parts){
sb.append(part.getName()).append(" ");
}
return sb.toString();
}
public double getPrice(){
double price = 0;
for ( Part part: parts){
price += part.getPrice();
}
return price;
}
}
public class CompositeDemo{
public static void main(String args[]){
Part engine = new Engine("DiselEngine",15000);
Part trunk = new Trunk("Trunk",10000);
Part body = new Body("Body",12000);
Car car = new Car("Innova");
car.addPart(engine);
car.addPart(trunk);
car.addPart(body);
double price = car.getPrice();
System.out.println("Car name:"+car.getName());
System.out.println("Car parts:"+car.getPartNames());
System.out.println("Car price:"+car.getPrice());
}
}
output:
Car name:Innova
Car parts:DiselEngine Trunk Body
Car price:37000.0
Explanation:
Part is a leaf
Car contains many Parts
Different Parts of the car have been added to Car
The price of Car = sum of ( Price of each Part )
Refer to below question for Pros and Cons of Composition and Inheritance.
Prefer composition over inheritance?
as another example, consider a car class, this would be a good use of composition, a car would "have" an engine, a transmission, tires, seats, etc. It would not extend any of those classes.
Composition is where something is made up of distinct parts and it has a strong relationship with those parts. If the main part dies so do the others, they cannot have a life of their own. A rough example is the human body. Take out the heart and all the other parts die away.
Inheritance is where you just take something that already exists and use it. There is no strong relationship. A person could inherit his fathers estate but he can do without it.
I don't know Java so I cannot provide an example but I can provide an explanation of the concepts.
In Simple Word Aggregation means Has A Relationship ..
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.
Why Use Aggregation
Code Reusability
When Use Aggregation
Code reuse is also best achieved by aggregation when there is no is a Relation ship
Inheritance
Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
Using inheritance in Java
1 Code Reusability.
2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).
Inheritance between two classes, where one class extends another class establishes "IS A" relationship.
Composition on the other end contains an instance of another class in your class establishes "Has A" relationship. Composition in java is is useful since it technically facilitates multiple inheritance.
Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Another difference which comes from this fact is that by using Composition you can reuse code for even final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition you can reuse code from many classes as they are declared as just a member variable, but with Inheritance you can reuse code form just one class because in Java you can only extend one class, because multiple Inheritance is not supported in Java. You can do this in C++ though because there one class can extend more than one class. BTW, You should always prefer Composition over Inheritance in Java, its not just me but even Joshua Bloch has suggested in his book
I think this example explains clearly the differences between inheritance and composition.
In this exmple, the problem is solved using inheritance and composition. The author pays attention to the fact that ; in inheritance, a change in superclass might cause problems in derived class, that inherit it.
There you can also see the difference in representation when you use a UML for inheritance or composition.
http://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html
Inheritances Vs Composition.
Inheritances and composition both are used to re-usability and extension of class behavior.
Inheritances mainly use in a family algorithm programming model such as IS-A relation type means similar kind of object. Example.
Duster is a Car
Safari is a Car
These are belongs to Car family.
Composition represents HAS-A relationship Type.It shows the ability of an object such as Duster has Five Gears , Safari has four Gears etc. Whenever we need to extend the ability of an existing class then use composition.Example we need to add one more gear in Duster object then we have to create one more gear object and compose it to the duster object.
We should not make the changes in base class until/unless all the derived classes needed those functionality.For this scenario we should use Composition.Such as
class A Derived by Class B
Class A Derived by Class C
Class A Derived by Class D.
When we add any functionality in class A then it is available to all sub classes even when Class C and D don't required those functionality.For this scenario we need to create a separate class for those functionality and compose it to the required class(here is class B).
Below is the example:
// This is a base class
public abstract class Car
{
//Define prototype
public abstract void color();
public void Gear() {
Console.WriteLine("Car has a four Gear");
}
}
// Here is the use of inheritence
// This Desire class have four gears.
// But we need to add one more gear that is Neutral gear.
public class Desire : Car
{
Neutral obj = null;
public Desire()
{
// Here we are incorporating neutral gear(It is the use of composition).
// Now this class would have five gear.
obj = new Neutral();
obj.NeutralGear();
}
public override void color()
{
Console.WriteLine("This is a white color car");
}
}
// This Safari class have four gears and it is not required the neutral
// gear and hence we don't need to compose here.
public class Safari :Car{
public Safari()
{ }
public override void color()
{
Console.WriteLine("This is a red color car");
}
}
// This class represents the neutral gear and it would be used as a composition.
public class Neutral {
public void NeutralGear() {
Console.WriteLine("This is a Neutral Gear");
}
}
Composition means creating an object to a class which has relation with that particular class.
Suppose Student has relation with Accounts;
An Inheritance is, this is the previous class with the extended feature. That means this new class is the Old class with some extended feature.
Suppose Student is Student but All Students are Human. So there is a relationship with student and human. This is Inheritance.
Inheritence means reusing the complete functionality of a class, Here my class have to use all the methods of the super class and my class will be titely coupled with the super class and code will be duplicated in both the classes in case of inheritence.
But we can overcome from all these problem when we use composition to talk with another class . composition is declaring an attribute of another class into my class to which we want to talk. and what functionality we want from that class we can get by using that attribute.
No , Both are different . Composition follow "HAS-A" relationship and inheritance follow "IS-A" relationship . Best Example for composition was Strategic pattern .

Arbitrary Java enum argument

I'm fairly new to java, and am used to enums essentially beeing nothing more than a named list of integers.
Now I'm writing an implementation where a parent class has a couple of methods that take an enum value as argument. The enum will be defined in child classes, and will differ slightly. Since enums basically seem to behave like classes, this doesn't work the way I expected it to. Each enum defined will be considered a different type of object and the parent class will have to pick one of the defined enums to take as argument.
Is there a good way to make the parent class accept any enum defined in it's child-classes? Or will I have to write a custom class for this?
Edit: Here is my example, fixed as per Jon Skeets answer, for anyone who is looking into how to do this later on:
class Parent {
protected interface ParentEvent {}
private HashMap<ParentEvent, String> actions = new HashMap<ParentEvent, String>();
protected void doStuff(ParentEvent e){
if(actions.containsKey(e)){
System.out.println(actions.get(e));
}
}
}
class Child extends Parent {
enum Event implements ParentEvent {EDITED, ADDED, REMOVED}
public void trigger(){
doStuff(Event.REMOVED);
}
}
You could make your enums implement an interface, then give your parent class method a parameter of that interface type.
As you say, enums are rather different in Java. They're not named numbers - they're a fixed set of values, but those values are object-oriented (i.e. they can use polymorphism etc). Java enums pretty much rock, except for a few tricksy issues around initialization ordering.
if i understand you correctly, you want to have a common base class for your enum and want to define several unrelated sets of enums for the sub classes. This is not possible with java's typesafe enums, because they don't allow you to define a base class.
Of course it is not an option just to have one enum defined and always extend its values because this clearly violates the open close principle.
For such a use case I have fairly good experience with Josh Bloch's Typesafe Enum Pattern he describes in Effective Java
Just introduce your super class here and make distinct sub classes for each of enum values your client classes need.
I'm not sure, but maybe this is what you want:
public abstract class EnumTest<E extends Enum<E>> {
public abstract void frobnicate(E value);
}
public class Derived extends EnumTest<Derived.DerivedEnum> {
public void frobnicate(DerivedEnum value) {
System.out.println(value);
}
public static enum DerivedEnum {
FOO, BAR,
}
}
You could define the enums in their own file if they're applicable to different classes. They don't need to be nested within a class.
You can't extend one set of enums from another though.
It took me a while to get out of the mindset of an enum 'just being an integer'.

Categories

Resources