Imagine I have an abstract class like this:
public abstract class Device {
public Device(DeviceModel model){
// ...
}
public abstract boolean isBuildable();
}
Then I have an implementation of it that might look like this:
public final class Floor extends Device {
// ...
#Override
public void boolean isBuildable(){
return false;
}
}
Here, each Device subclass returns either true or false to #isBuildable(). But each instance of Floor always returns false. Another implementation of Device may return true. That sounds like a static data : it does not depends on the current instance, but on the type of the Device.
Currently, I'm creating an instance of the class to get its value, as #isBuildable() isn't static. But I think that's poor code design.
So, what I'm trying to achieve here is like creating abstract static method. I've seen this question that doesn't help so much. I would forces the implementation of #isBuildable (this time as static) in all subclasses of Device, so that I can invoke Floor.isBuildable() or something else of the same kind.
Here I can't control all the source, so I can't use reflectivity on that.
Hope you understand this weird question !
If you need to store class-specific (not instance-specific) information, custom annotations may be the way to go.
This require a function using reflection to access that piece of information, which could be overkill in a small project, but should be no problem in a larger framework or similar project.
In Java, static methods cannot override other static methods, so what you want to do is not possible.
Since Java has no real type variables (the type variables used for generics do not survive until run time) you would need an instance anyway to determine which overridden static method to call.
Suppose you have a class Device with two subclasses, Floor and Ceiling, all of which have a method called foo(). Since there are no run-time type variables, T.foo() cannot work, and Device.foo(), Floor.foo() and Ceiling.foo() all specify exactly which method to call.
There are a few solutions/workarounds:
Call the right method through reflection. You will lose any static type checking.
Introduce a companion enum or class which contains the information about your types. For example:
public class DeviceType {
private final boolean buildable;
private DeviceType(boolean buildable) {
this.buildable = buildable;
}
public boolean isBuildable() {
return buildable;
}
}
public class Floor extends Device {
public static final DeviceType DEVICE_TYPE = new DeviceType(false);
...
}
Now you can pass around Floor.DEVICE_TYPE as a kind of representation of the class which contains the information you want.
Related
I have a method which adds Objects to an static list like this:
#PostConstruct
protected void registerToTransactionList() {
TransactionValidator.registerTransactionList(this);
}
registerTransactionList method just adds "this" to the static list, this method is in BalanceTransactionValidator class which extends TransactionValidator (owner of static list),the problem is all subclasses of BalanceTransactionValidator class are added to static list either,and if I override registerToTransactionList method in them like this:
#Override
#PostConstruct
protected void registerToTransactionList() {
}
It doesn't add subclasses but doesn't add BalanceTransactionValidator either. Can anybody help me on this? Please notice sublasses are overriding this method by default.
make the method private to block the visibility
private void registerToTransactionList() {
}
or make the method final to block it from been override
protected final void registerToTransactionList() {
}
There are two ways of achieving that:
Keep your method as it is; but then you have to actively check for the type of your objects before externally calling that method
Change your whole logic and make that method private
It won't help to make the method final as suggested in one of the comments - your problem is not that subclasses are overwriting that method; in essence, you have a design problem: you wish that subclasses should not invoke that method at all.
So, the only real option that makes sense here is "2.". You see, by having public method on a class that you want to be extended you are implicitly saying: it is perfectly fine to call that method; on any object that is instance of the base class (or child class!).
And in your case, that is not true: you actually do not want that the code behind this method runs for child classes. Then you shouldn't put that method in the list of public/protected methods of your base class!
Finally: you might want to step back and do some reading about good OO design. Class hierarchies do not fall from the sky: you willfully design them for a certain purpose. In other words: there is more to inheritance than just putting some "A extends B" on your class declaration. You have to understand each and every method on your B class; and how your child classes should deal with them!
EDIT: after some more thinking, I guess you are doing things "the wrong way", like:
class BaseClass {
public final void doRegistration() {
BaseClass toRegister = getObjectForRegistration();
if (toRegister != null) { ... register toRegister ...
}
protected BaseClass getObjectForRegistration() {
return null;
}
With that code, you could then put
protected BaseClass getObjectForRegistration() {
if (this instanceof ClassThatShouldBeRegistered) {
return this;
}
return null;
}
into that one class that wants to be registered. Probably there could be even nicer ways of doing so; but after some thinking I don't see how we could avoid the instanceof. But the above code should work; and it only requires specific code only in your base class and in that one class that wants to register something.
So as part of a car rental system I need to write classes to represent large and small cars, the difference between these being that they have different size tanks and consume fuel at different rates. Currently my approach is to have an interface, Car, implemented by an abstract class AbstractCar, which is extended by two concrete classes SmallCar and LargeCar. However this is my first time using interfaces and abstract classes (we are just covering them in class and this assignment is designed to assess our knowledge of them) and I'm having trouble knowing what to place in what class.
The fill method implementations are exactly the same, they just need to refer to the correct value of FUEL_CAPACITY, so it feels that I should be implementing these methods in the AbstractCar class, but then I don't know how to get them to refer to the correct FUEL_CAPACITY values. The field fuelLevel is also obviously held by all cars so it feels that I should declare it in AbstractCar, but then I cannot access it from the subclasses without removing its privacy.
Would anyone be able to help me figure out what I'm doing wrong or misunderstanding about interfaces and inheritance? One thing I've been considering is producing an enum CarType, having AbstractCar hold a CarType as a field and all implementation is done in the AbstractCar class using if statements to switch to the correct FUEL_CAPACITY value, and simply using SmallCar and LargeCar as constructors or factory classes without much or even any actual implementations.
Thanks in advance for any help I realise its a bit long winded, however I try to make sure I'm fully understanding the concepts we are learning and that I'm implementing them correctly rather than just botching together something that 'works' but might not necessarily be the correct or most elegant solution.
You can transfer the logic to the AbstractCar with the values like you pointed out. Then just set those values in the constructor of SmallCar and LargeCar. This would be one approach. Like you pointed out, you always have to have the common logic in the parent class. You want to avoid duplicate code. Then you just have to make sure you set different values in the constructor. And if you know the fix value (as you do from the given example), you can even omit giving parameters to SmallCar or LargeCar constructors and just set those fixed values in the super() call inside the constructor.
Here is the implementation of my solution.
The interface Car, where I REMOVED the getFuelMethod() method since the access level has to be protected:
public interface Car {
RegistrationNumber getRegistration();
int getFuelCapacity();
// int getFuelLevel(); this can not be implemented
// all methods in an interface are PUBLIC
// so you have to lower the access level by removing it from the interface
// HERE goes the rest of the method signatures
}
}
The abstract class AbstractCar:
public abstract class AbstractCar implements Car {
// this is the common variable
// that is why we save it in the parent class
private int fuelCapacity;
private int fuelLevel;
// we forward the value to the parent constructor with the super call
public AbstractCar(int fuelCapacity) {
this.fuelCapacity = fuelCapacity;
// I set the value to 0 for the start, but
// you can also pass the value to the super call,
// same as fuelCapacity - it is up to you
this.fuelLevel = 0;
}
// The getters and setter allow us to retrieve the values
// from the abstract class through capsulation!
// here we have the getter to be able to retrieve the value from SmallCar and LargeCar
public int getFuelCapacity() {
return.fuelCapacity;
}
public void setFuelCapacity(int fuelCapacity) {
this.fuelCapacity = fuelCapacity;
}
protected int getFuelLevel() {
return fuelLevel;
}
protected void setFuelLevel(int fuelLevel) {
this.fuelLevel = fuelLevel;
}
// HERE goes the rest of the code
}
Here is the SmallCar implementation:
public class SmallCar extends AbstractCar {
private static final int FUEL_CAPACITY = 45;
public SmallCar() {
// we set the value in the parent class
super(FUEL_CAPACITY);
}
public int drive() {
// HERE goes the logic for drive for SmallCar. Same method is needed
// in the LargeCar class, because the logic differes.
}
// HERE goes the rest of the code
}
If you just want to hide FUEL_CAPACITY from the class user but not from the further developers, you can declare it as protected in the AbstractCar and initiallize it with a proper value in the child classes. Also I would declare a getter method getCapacity() in the AbstractCar which returns this value.
If your Capacity is only one property (only data) of Car, use #Jernej K approach, but if calculating the capacity may have some logic, use this:
Best way is to use abstract methods. you put a method to abstract Integer getCapacity(); in your abstract class
public abstract class AbstractCar implements Car {
private final RegistrationNumber registration;
private boolean isRented;
AbstractCar() {
this.registration = RegistrationNumber.getInstance();
}
public RegistrationNumber getRegistration() {
return registration;
}
public boolean isRented() {
return isRented;
}
//You can use this method in other methods of AbstractCar, but is implemented in your concrete classes
public abstract Integer getCapacity();
public boolean isFull() {
if (fuelLevel == getCapacity()) {
return true;
} else return false;
}
}
and then use it in other functions. and in your concrete class, you define the body of method:
public Integer getCapacity(){
//Your logic to calculate capacity for every concrete class here
}
I'm creating a Mario clone where everything on the screen is an instance of ScreenElement. A ScreenElement is Landable if it can be landed on by Mario.
public class ScreenElement {
public boolean isLandable() {
return false;
}
}
Some classes override isLandable, for example:
public class GrassBlock extends ScreenElement {
#Override
public boolean isLandable() {
return true;
}
}
And classes that don't override isLandable should inherit it from the closest super class that does. That is to say, I need polymorphism.
Now this all works fine as long as isLandable is an instance method. However whether or not a given ScreenElement is Landable depends on the class, not the instance. So isLandable should really be static. But if I make it static, I cannot override it or inherit in sub classes that don't explicitly define it. Is there a simple workaround to this problem.
EDIT:
I do realize that the way I have it set up right now, it is working correctly but the reason I am bringing this up is because I have encountered a problem. Given a class that extends ScreenElement, I need to find out the result of isLandable. The only thing I could think of was this:
private <S extends ScreenElement> boolean isThisLandable(Class<S> category) {
return category.newInstance().isLandable();
}
I have to create a new instance to figure out something that doesn't depend on the instance, and this seems unnatural.
EDIT 2: Here's the specific piece of code that I'm dealing with.
private <S extends ScreenElement> S getGenericScreenElement(Mario mario, Class<S> category) {
for (ScreenElement element : screenElements) {
if (category.isInstance(element)) {
S elementToTest = category.cast(element);
if (elementToTest.isLandable()) {
//return elementToTest if it matches additional criteria
}
}
}
return null;
}
You're overthinking this.
In a nutshell, this code is doing exactly what you want it to do.
Here's what happens.
Your parent class, ScreenElement, defines by the isLandable() method by default, and it is always set to return false. By creating a new class that is a ScreenElement, if they wish to change this behavior, they must override that method to do so.
The fact that your GrassBlock does override this method is indicative that any instance of a GrassBlock will register true if its isLandable() property is checked.
With your code revision, you're still overthinking this.
All you need to do when you attempt to use an instance of ScreenElement - be that an instance of ScreenElement or any of its children - is to just call the method.
You shouldn't care about that property until you decide to check it, during its run. The way you're checking it now makes very little sense at all.
As an example:
ScreenElement vanillaElement = new ScreenElement();
GrassBlock block = new GrassBlock();
System.out.println(vanillaElement.isLandable()); // will print false
System.out.println(block.isLandable()); // will print true
More explicitly, with your sample code, you can greatly reduce it. Many of your statements to check against the type are unnecessary, especially when casting. You're guaranteed to have nothing more than a ScreenElement, and since isLandable() is defined on at least that, you will never run into a scenario in which you cannot call that method.
The above will turn your code into this. I leave the addition of your Mario parameter up to you since its purpose is unclear in this method.
private ScreenElement getGenericScreenElement(Mario mario) {
for (ScreenElement element : screenElements) {
if (element.isLandable()) {
//return element if it matches additional criteria
}
}
return null;
}
The fact that you need the methods to be overrideable and you want to do polymorphic dispatching means that they should not be static methods.
However whether or not a given ScreenElement is Landable depends on the class, not the instance.
So make the methods instance methods without using the instance state.
java.lang.Class has methods to test if a given type is:
isAnnotation
isArray
isEnum
isInterface
isPrimitive
but how does one test that an object of type Class (instanceof Class is true) represents a declared, non-abstract class rather than in interface, enum, primitive, array, etc. For example:
package org.acme;
public class ACME {
public ACME() {
}
public static void main(String[] args) {
Class clazz = Class.forName("org.acme.ACME");
// Expected I could use a clazz.isClass().
}
}
I was looking for a isClass method, but there isn't.
Update
I see the confusion generated by my question - while some people got my question.
I did some further research and found out that in .NET
http://msdn.microsoft.com/en-us/library/system.type.isclass.aspx,
there this is a isClass member and I was looking for a similar method in java.lang.Class.
I now know that the equivalent in Java is to test for all the other isXXX methods to find out that it's not a class.
It seems there's a disconnect in your question. Everything is a class (except primitives - the isPrimitive() method actually means the class is an autobox type).
Class clazz = Class.forName("org.acme.ACME");
// Expected I could use a clazz.isClass().
That would be redundant. You already know it's a class. Because you have an instance of Class.
It would appear that for some reason you would like to know it's not any of the types of classes the methods you list tell you, in which case you'd simply do a check to negate those options:
if (!clazz.isAnnotation() &&
!clazz.isArray() /* && ... etc */ )
{
// Not any of those things.
}
Class objects are singletons. Therefore, if you have an instance of any type, you can test that it is an exact class instance using:
theInstance.getClass() == TheTargetClass.class
As to testing whether a class is a "full" class, just negate all the test you mentioned. This first test is already an efficient filter... And do not forget .isSynthetic().
Not so readable but
object.getClass().getModifiers() < 30 //abstract classes are not included
or in a more readable way:
object.getClass().getModifiers() < Modifier.PROTECTED + Modifier.STATIC + Modifier.FINAL
seems to work, being more neat (but more obscure) than
!(!isInterface() && !isEnum() && !is ...)
A simple class can only have these modifiers:
public static final int PUBLIC = 0x00000001;
public static final int PRIVATE = 0x00000002;
public static final int PROTECTED = 0x00000004;
public static final int STATIC = 0x00000008;
public static final int FINAL = 0x00000010;
while abstract, interafce, enum or annotation has larger values (over 200).
You can see the Modifiers of a class by calling Modifier.toString(myClass.getModifiers()). The getModifiers() class returns the sum in hexa of all modifiers (as I have tested on some values; the implementation is native).
A partial solution:
You can try to execute the Class's newInstance method. If the class is abstract or an interface an InstantiationException will be thrown- Otherwise, you're good.
The problem is that creating a new instance in a class you don't know might have unknown effects, or the class might not have a default constructor.
Two options that should work for you:
You can do class instanceof Object
You can check all the other is...() methods. If they are all false you have a class.
I've come across some code that I can't share here but it declares a method WITHIN the paramter list of another method. I didnt even know that was possible. I dont really understand why its doing that. Can someone please explain to me some possible uses that you as a programmer would have for doing that? (Note: Since I can't show the code I dont expect an in-context explanation just generally)
Related:
What's the nearest substitute for a function pointer in Java?
Did the code look something like this?
obj.someMethod(myVar,3,new FooObject() {
public void bar() {
return "baz";
}
});
If so, then the method is not being passed to the other method as an argument, but rather an anonymous inner class is being created, and an instance of that class is being passed as the argument.
In the example above FooObject is an abstract class which doesn't implement the bar() method. Instead of creating a private class that extends FooObject we create an instance of the abstract class and provide the implementation of the abstract method in line with the rest of the code.
You can't create an instance of an abstract class so we have to provide the missing method to create a complete class defintion. As this new class is created on the fly it has no name, hence anonymous. As it's defined inside another class it's an anonymous inner class.
It can be a very handy shortcut, especially for Listener classes, but it can make your code hard to follow if you get carried away and the in line method definitions get too long.
In Java you can't pass methods as parameters. Could it have been passing not a method, but an anonymnous inner class?
This can be useful for passing behaviours between classes. Google "dependency injection" or "Inversion of control" for more information.
Have you ever seen the Functional Java?
It's a very interesting library that allows you programing like you would do in Scala.
I Wrote about this libs. I confess it is better to use in a more flexible syntax (BGGA closures) like Scala.
Using Functional Java with a high-order function like map on a list we have:
final List<Integer> numbers = list(1, 2, 3, 4, 5);
List<Integer> c = numbers.map(new F<Integer, Integer>() {
public Integer f(Integer arg) {
return arg * arg;
}
});
Another useful lib is lambdaj that offers nice ways to play like in Functional (FP) Programming.
Java has a limited syntax compared to FP languages. But you can still take some advantages of FP style, but you must be creative!
using java.lang.reflect.Method
example
public void callMethod(Method aMethod, int value) throws Exception {
aMethod.invoke(this, value);
}
public void print(Integer value) {
System.out.print(value);
}
public void println(Integer value) {
System.out.println(value);
}
public void demo() throws Exception {
Method println = this.getClass().getMethod("println", Integer.class);
Method print = this.getClass().getMethod("print", Integer.class);
callMethod(println, 10);
callMethod(print, 10);
}
The nearest thing to passing a function pointer in Java is passing an anonymous instance of an abstract class or interface. For example, a generic function type can be encoded in an interface like this:
public interface F<A, B> {
public B f(final A a);
}
You can then expect a method in another method's argument list:
public List<B> map(List<A> as, F<A, B> f) {
...
}
And you can call it with an anonymous instance of that interface:
map(myList, new F<Integer, String>() {
public String f(Integer i) {
return String.valueOf(i);
}
});
There's a library called Functional Java that exploits exactly this idea for great benefit glorious language Java.
It's not, per se, legal syntax in Java. Was it perhaps creating a new instance of an anonymous class?
You can also do something like this:
final Predicate somePredicate = new Predicate<Item>()
{
#Override
public boolean apply(Item item)
{
return item.someProperty().equals(something);
}
}
And use it like this:
List<Item> filteredList = filter(list, somePredicate);
I've done stuff like that before. I've also written methods that use a closure to build and return an anonymous implementation of an interface in a similar way:
Predicate isSomeColor(final Color color)
{
return new Predicate<Shape>()
{
#Override
public boolean apply(Shape shape)
{
return shape.getColor().equals(color);
}
}
}
List<Shape> redShapes = filter(shapes, isSomeColor(Color.RED);
All of this is still anonymous inner classes. Nowhere am I actually naming the class itself, I just have a reference to an instance of the class.
this is called reflection. there is a whole library of objects representing stuff like constructors, methods and such.
you can use it, for instance, in order to call a dynamic method that is determined on runtime.
Yes, declaration of a method within the parameter list of another method can be done. You can check out java.lang.reflect.Method
Using reflection, you retrieve a Method object representing the method you wish to pass as a parameter. Then you can call Method to invoke to make a call to that method.
Moreover, you can refer "Functional programming in the Java language" (http ://www.ibm.com/developerworks/java/library/j-fp.html) which can give you inside-out with examples.
The answers above are varying as to whether or not it is even possible. Is it possible through reflection? Is possible through the use of an anonymous inner class? We need to clarify this.
the closest to a function argument is
an instance of a anonymous class with exactly one method.
Runnable a = new Runnable(){
run(){
System.out.println("hello");
}
}
myMethod(a);
not pointer, but still you can write functions inline with some trick.
check my answer on another thread