java base class that extends a paramater class/interface - java

I have some base class Entity. I want to allow users of Entity to create instances of Entity that extend some given super class T (as if Entitys declaration was Class Entity extends T). I'm not aware of what T actually is, so I want Entity to be modular in that respect. If that's not possible I'm ok with Entity implementing a given interface T as well.
Things like public class Entity<T> extends T and public class Entity<T> implements T do not work. ("Cannot refer to the type parameter T as a supertype").
So my questions are:
1) is this at all possible to achieve in java ? some other language ?
2) if so, how ?
3) usually when java puts up hurdles like that it means something is wrong with my design, so how would you create this functionality (I guess what I'm looking for is basically multiple inheritance from Entity and T, can this be done ?).
EDIT: clarification - I want to achieve mixin type behavior while requiring as little as possible from the caller (creating a subclass of T which delegates calls to an Entity instance would demand way too much from the caller). is there no other way to do this ?

Java doesn't support multiple inheritance; a given class can't be a direct subclass of more than one class.
However, if Entity is an interface, you can do it using an intersection bound.
For example, to code a method that accepts an instance that is a subclass (not necessarily a direct subclass) of SomeClass and that implements Entity:
public <T extends Entity & SomeClass> void doSomething(T t) {
}

template <class A>
class B : public A
{
Possible in C++ at least.
I have used this once in my own work, to add behavior to two classes that are very closely related (one inheriting from the other). It struck me only much later that the Decorator Pattern might have worked as well. Perhaps you can also consider it.

The key in your question is when you said that you want to "create instances of Entity that extend some given super class T". An object (instance of a class) never extends a class. Only classes extend other classes.
What you probably want is to use interfaces. Let Entity be an interface and create classes that implement Entity and then instantiate those classes.

No thats not how it works in Java. You might want to consider composition instead of inheritance.
I'm kind of reading between the lines here, but are these Entities in a game engine? A component system would work well...
http://gameprogrammingpatterns.com/component.html
Here's a quick example...
class Entity {
List<Component> components;
void update() {
for(Component component: components) {
component.update(this);
}
}
}
interface Component {
void update(Entity parent);
}
class MovementComponent implements Component ...
class AnimationComponent ...
class BehaviourComponent ...

Related

How can I restrict arguments of methods in abstract classes for subclasses that use them?

I've been trying to design a set of classes to model a classic RPG. I've found myself confused on how to solve this one issue, however: how do I force the use of character-type (e.g. Tank, Healer, DPS) specific spells/equipment, etc. in an abstract class. The example below better articulates what I mean.
I've got an abstract PlayableCharacter class which all character-types inherit from:
public abstract class PlayableCharacter {
private Set<Spell> mSpells;
...
public void addSpell(Spell spell) {
mSpells.add(spell);
}
}
For example:
public class Healer extends PlayableCharacter { ... }
public class Tank extends PlayableCharacter { ... }
Note the Set of Spell in the abstract class. I would like it if each subclass of PlayableCharacter could use its addSpell method but with the restriction that the type of Spell correspond to the PlayableCharacter subtype.
For example I have these Spell classes:
public abstract class Spell { ... }
public class HealerSpell extends Spell { ... }
public class TankSpell extends Spell { ... }
I only want Healers to use HealerSpells and Tanks to use TankSpells, etc. For example:
PlayableCharacter tank = new Tank();
tank.addSpell(new TankSpell()); // This is fine
tank.addSpell(new HealerSpell()); // I want to prevent this!
I thought of giving each subclass of PlayableCharacter it's own Set of subclass-specific Spells, but that creates a lot of code duplication.
I also tried making PlayableCharacter.addSpell marked as protected, then each subclass would have to implement an interface like this:
public interface Spellable<T extends Spell> { void addClassSpell(T spell); }
and each subclass that implements it would call super.addSpell(spell); but that lead to more code duplication and nothing was forcing those implementations to do the super call.
Is my strategy fundamentally flawed in some way? Any advice? I feel like this issue will keep getting worse as I add more character-type-specific equipment, traits, and so on.
I wouldn't do it that way (via type inheritance). It would be better to add characteristics to a Spell itself because it's a spell, which can be cast by a certain character only. Also, a specific spell can be cast to a certain character type only. These rules belong to a spell, not to a character.
Spell rules can be checked in a runtime by a separate class or by a Spell class itself inside a cast() method or another one.
so far what you have is good
the rest of the stuff, think more strategy pattern than super call
so abstract class can have algorithm that does step1, step2, step3 with possible parent implementation
child classes can override it, but only override parts that is different
when you call algorithm, it performs all steps
Steps themselves could be different class that has logic, if everything becomes too big
maybe have each subclass of playable character store the class (or classes) of subspells that are allowed. then do an if(spell instance of allowedSpell) ...

How to prohibit a subclass from having a method?

In my Java project, I have the method addType1AndType2() which has windows where you expand lists and select objects from the list. It was very complicated and time consuming to create, as things must be scrolled and xpaths keep changing. There are two lists in this which are actual names but, due to company proprietary info, I will just call them Tyep1 and Type2.
Now I have an UpdateType1 class which uses all the complicated methodology in the AddType1AndType2 but has nothing related to Type2 in it. I could copy the AddType1AndType2 and cut everything I do not need, but that would be replicating and changes would have to be duplicated in both classes. This defeats the purpose of inheritance and reusability.
I can make a class UpdateType1 extends AddType1AndType2{} which I have done. But there are still methods like selectType2Value() which are inherited but not possible in the subclass.
If I do an #Override and declare the class as private in the sub class, I get an error that I cannot reduce the visibility in a subclass.
Any idea what I can do? Right now I am just putting a throw new AssertError("Do not use") but that seems kind of lame. Is there a better thing to do that would even give a compile-time error rather than an assert at run time, or is this the best way?
The thing is: your model is wrong.
Inheritance is more than just putting "A extends B" in your source code. A extends B means: A "is a" B.
Whenever you use a B object, you should be able to put an A object instead (called Liskov substitution principle).
Long story short: if B has methods that A should not have ... then you should not have A extends B.
So the real answer is: you should step back and carefully decide which methods you really want to share. You put those on your base class. Anything else has to go. You might probably define additional interfaces, and more base classes, like
class EnhancedBase extends Base implements AdditionalStuff {
Edit: given your comment; the best way would be:
Create interfaces that denote the various groups of methods that should go together
Instead of extending that base class, use composition: create a new class A that uses some B object in order to implement one/more of those new interfaces.
And remember this as an good example why LSP really makes sense ;-)
Create the interfaces
public interface IAddType1 {... /* methods signtatures to add Type1 */}
public interface IAddType2 {... /* methods signtatures to add Type2 */}
public interface IUpdateType1 {... /* methods signtatures to update Type1 */}
then your current code at AddType1AndType2 will become just a base helper class:
public abstract class BaseOperationsType1AndType2{
//code originally at AddType1AndType2: methods that add Type1 and Type2
}
then your new AddType1AndType2 class will be:
public class AddType1AndType2
extends BaseOperationsType1AndType2,
implements IAddType1 , IAddType2 {
//nothing special.
}
and your new UpdateType1can be defined as
public class UpdateType1
extends BaseOperationsType1AndType2
implements IUpdateType1 {
//
}
Voila.
You can use 'final' keyword to prohibit extending a method in a subclass.
A method with a 'final' modifier cannot be overriden in a subclass.

Java allowing multiple inheritance

I am confused regarding a concept in multiple inheritance.
I have three classes A, B and C.
Class A {
// ...
}
Class B extends A {
// ...
}
Class C extends B {
// ...
}
I know this is a bad practice of multiple inheritance and I also read java allows multiple inheritance through interfaces. But I am not getting any error in the above code. Please can anyone explain me with a clear example without using interface.
Thanks!!
This is not multi-inheritance. Each class has exactly one direct super class. If your example was considered multi-inheritance, you wouldn't be able to use the extends keyword at all, since each class already extends by default the Object class.
Multi-inheritence would be
class C extends A,B {}
And that's illegal in Java.
Your code does not contain multiple inheritance, and is, indeed, legal Java syntax. Multiple inheritance refers to a case where a class directly extends two superclasses. For example:
public class MyClass extends MyFather, MyMother {
}
Note that this is, of course, illegal Java syntax.
"Multiple inheritance" in Java basically means inheriting multiple interfaces, not inheriting multiple implementations.
Now, there is a new feature of Java 8 that allows you to do something like multiple inheritance of actual implementations, via interfaces and something called default methods. I would strongly encourage you to really master the basics of Java first before trying them. Once you are ready, here is a good tutorial on default methods.
The code you have written above is an example of Multilevel inheritance not Multiple Inheritance.
Multiple Inheritance is like :
class A extends B,C {
//this code is not valid in JAVA
}
And, if you want to use interfaces for implementing a structure like multiple inheritance, then you could use:
interface test_interface1{
/*all the methods declared here in this interface should be the part
** of the class which is implementing this current interface
*/
}
Similarly :
interface test_interface2{
}
So, create a class TestClass like :
class TestClass implements test_interface1,test_interface2 {
//now you have to use each and every method(s) declared in both the interfaces
// i.e. test_interface1 & test_interface2
}
You could also use a syntax like:
class TestClass extends AnyClass implements test_interface1,test_interface2 {
/* but do keep in mind - use extends keyword before implements
** and now you know you cannot use more than 1 class names with extends keyword
** in java.
*/

java generics, how to extend from two classes?

I want to have a Class object, but I want to force whatever class it represents to extend class A and also class B.
I can do
<T extends ClassA & ClassB>
but it is not possible to extend from both classes, Is there a way to do this?
In java you cannot have a class which extends from two classes, since it doesn't support multiple inheritance. What you can have, is something like so:
public class A
...
public class B extends A
...
public class C extends B
...
In your generic signature, you can then specify that T must extend C: <T extends C>.
You could give a look at Default Methods (if you are working with Java 8), which essentially are methods declared within interfaces, and in Java, a class can implement multiple interfaces.
A simple way for this problem is inheritance.
public class A { // some codes }
public class B extends A { }
<T extends A>
Java does not have multiple inheritance as a design decision, but you may implement multiple interfaces.
As of Java 8 these interfaces may have implementations.
To use multiple classes there are other patterns:
If the parent classes are purely intended for that child class, but handle entirely different aspects, and were therefore separated, place them in a single artificial hierarchy. I admit to doing this once.
Use delegation; duplicate the API and delegate.
Use a lookup/discovery mechanism for very dynamic behaviour.
public T lookup(Class klazz);
This would need an API change, but uncouples classes, and is dynamic.

How is abstract class different from concrete class?

I understand WHY we need Abstract Class in Java - to create sub-classes. But the same can be achieved by concrete class. e.g. Class Child extends Parent. Here Parent can very well be abstract & concrete. So why do we have ABSTRACT??
Abstract classes cannot be instantiated directly. Declaring a class as abstract means that you do not want it to be instantiated and that the class can only be inherited. You are imposing a rule in your code.
If you extend your Parent/Child relationship example further to include a Person class then it would make good sense for Person to be abstract. Parent is a concrete idea and so is child. Person is an abstract concept in reality as well as in code.
One benefit is that you explicitly define and protect the idea of the abstract class. When you declare a class as an abstract there's no way that you or anyone else using your code uses it incorrectly by instantiating it. This reasoning is similar to why we specify functions and fields as public, private or protected. If you declare a function or member as private you are in effect protecting it from improper access from client code. Privates are meant to be used within the class and that's it. Abstract classes are meant to be inherited and that's that.
Now, do you have to use abstract classes and define functions and fields as private instead of public? No, you don't. But these concepts are provided to help keep code clean and well-organized. The abstract class is implemented in all object-oriented languages to my knowledge. If you look around you will see that C++, C#, VB.NET etc. all use this concept.
A better, specific example:
In the example above the Shape class should be abstract because it is not useful on its own.
Abstract class means it is abstract not complete. It needs another class to complete it and/or its functionalities. You need to extend the abstract class. It will be useful with Certain class eg. Fruit all fruits have the same property like color. But you can have different properties for different fruits like is it pulpy such as orange or not eg Banana etc.
I know this is an old question but it looks like the poster still had some questions about the benefit of using an abstract class.
If you're the only one who will ever use your code then there really is no benefit. However, if you're writing code for others to use there is a benefit. Let's say for example you've written a caching framework but want to allow clients to create their own caching implementation classes. You also want to keep track of some metrics, like how many caches are open, hypothetically. Your abstract class might look something like this:
public abstract class AbstractCache {
public final void open() {
... // Do something here to log your metrics
openImpl();
}
protected abstract void openImpl() { }
}
On its own the AbstractCache class is useless and you don't want clients to try to instantiate one and use it as a cache, which they would be able to do if the class was concrete. You also want to make sure they can't bypass your metric logging, which they would be able to do if you just provided them a Cache interface.
The point of abstraction is not to create sub-classes. It's more about creating Seams in your code. You want code to be test-able and decoupled which lead to the ultimate goal of maintainability. For similar reasons, abstraction also buys us the ability to replace a bit of code without rippling side effects.
An abstract class is meant to be used as the base class from which other classes are derived. The derived class is expected to provide implementations for the methods that are not implemented in the base class. A derived class that implements all the missing functionality is called a concrete class
According to my understanding
Abstract Class is a class which just describes the behavior but doesn’t implement it.
Consider this Java example for Abstract Class:
public interface DoSomething(){
public void turnOnTheLight();
}
Concrete Classes are those, which are to be implemented.
For Example:
public abstract class A(){
public void doIt();
}
public class B extends A(){
public void doIt(){
//concrete method
System.out.println(“I am a Concrete Class Test”);
}
}
In other words, A concrete class in java is any such class which has implementation of all of its inherited members either from interface or abstract class.
For those who seek only differences in pure technical approach, the clearest difference between concrete parent classes and abstract parent classes is the obligation for children to include/implement specific methods.
A concrete parent class cannot force/oblige its children to include/implement a method. An abstract parent class oblige its children to do that by declaring abstract methods.
Apart from the above, it comes to design and functional requirements to dictate the use of abstract class. Such examples can be found on javax.servlet.http.HttpServlet class

Categories

Resources