Can I cast an object to class with interface(s)? - java

I have a object obj and I want to cast it to View that implements interface Tool.
class Whatever {
View viewObj;
Tool toolObj;
...
public void setViewTool( View obj )
{
viewObj = obj;
toolObj = (Tool) obj;
}
...
}
I want to avoid creating two objects to handle the situation or using one that I have to cast each time I want to call an implemented method of View or Tool.
The same thing, if possible, when using two interfaces or more. I recall a language I could do something like this View<Tool, and, others, interfaces>.
Example
I think the title and the first line of the question is clear. But, may it's not.
I have three tools to show in the app. One is made extending LinearLayout, and the others two, FrameLayout. These view objects has to implements Tool interface because there are methods called when it inits, finishes and when the user do some gestures. But, it's a view too, and when I need to show, it needs to call things like setLayout, addView, animate.
Just to clarify, it's works fine in the example above. But I have to set two variables to handle the same object, one for doing stuff related to the view aspect, and one to the Tool interface.
I can't say generic class doesn't work but the way I have tried, it doesn't. What I wish, was the possibility of create a class property as private (View implements Tool) myObj;.
Now, I almost sure it's not possible from this other answer: Java - Defining a member that extends class A and implements interface B

If your question is
I know I can cast an object (A) to another (B), but can I do it if the B class implement an interface (C) ?
Then the answer is yes. It does not change anything that the class B implement C or not. But as for any object cast you can do it only if the instance a of A is also an instance of B. You can test it like that :
A a = new A()
if(a instanceof B) {
//a is an instance of B
}
If the instance a of A is also an instance of B it means that it implements C. So you can do
C c = (C) a;
B b = (B) a;

Related

Setting a class variable as the output of a method in an abstract class

I am extending on an existing library that has an abstract class (let’s call it ‘A’) with an abstract method (let’s call it ‘A.a()’) that returns an instance of another class (‘B’). I seek to have information on which instances of B ‘belong’ (were created by) which instances of A. The way that I was thinking about doing this was to use the returned instance of B from A.a() as a class variable for A. The problem is that, in the library, A has already been implemented over fifty times and is called many more times than this.
Some further background on the library, the classes A and B are part of a larger recursive pattern where an instance of A contains children (other instances of A) developing a hierarchy. The hierarchy of A is developed first then A.a() is used to develop the hierarchy of B (by creating instances of B also with children) however neither ‘know’ anything about the other which is what I am trying to change.
Currently, I have designed a new method in A ('A.c()') that can be called at the return statement of each of the implementations of a() in the subclasses. The A.c() simply takes the instance of B that was being returned, sets a variable to that instance and then returns that instance of B to the return statement of A.a().
The classes and methods that A and B relate to in the actual library are: Atom (A), Box (B) and createBox (A.a()). A.b and A.c() I have included as they are used in my current solution (see previous paragraph).
public abstract class Atom {
private Box b = null;
public abstract Box createBox()
protected Box setB(Box box){
this.b = box;
return box;
}
}
public class Alpha extends Atom {
...
public Box createBox(){
...
Box box = new Box();
...
return setB(box);
}
}
I feel this is not a neat nor manageable solution. Ideally I’d like to just be able to write the code such that whatever A.a() returns, a variable in A is set to this. Does anyone know a way of achieving this or could perhaps suggest a broader strategy that I should look at employing to tackle the problem at a different level?
Any help particularly guidance rewording the question or requests for more info would be appreciated! I've been battling this one for a couple of days now and am sure I'm missing something.
Thanks in advance!
EDIT 1
The library is jlatexmath by scilab. (http://forge.scilab.org/index.php/p/jlatexmath/downloads/)
EDIT 2
Emboldened the purpose of the change to the library and updated the class and method names to reflect the library.
Thinking of classes as owning instances is very much not Java thinking, and will lead you in painful paths.
What you should be thinking about is having a factory class that produces instances and keeps track of them. That factory might want to be a singleton. You do not want a library to be keeping track of the objects, you want your own structure that produces your particular set of objects and keeps track of them however you need to keep track of them.
Update: exchange a() and c()
I would recommend to put the "tracing" code into abstract class A. This resolve the issue having already many A-sub-classes. Furthermore, I would use generics to be able to put all code you need into class A. The following is just a sketch to give an idea:
public abstract class A<T extends B> {
private T b = null;
protected abstract T a();
public final T c() {
this.b = a();
return this.b;
}
}
public class Beta extends B {
...
}
public class Alpha extends A<Beta> {
...
protected Beta a(){
return new Beta()
}
}
So you track your relationship between A and B in the public method and use an abstract protected method to create Bs (ie, you reverse the functionality of you original methods a() and c()). This design make the implementation of Alpha.c() straight forward. Furthermore, using generics, it allows you to put all code into A and instantiate different B in different subclasses of A.

Why can a super class be initialized as a child class in Java?

In a nutshell, how and why is this possible:
Object obj=new MyClass();
Object is the superclass of all objects, therefore MyClass is a child class of Object. In general, in Java, Why is it possible to use the constructor of a child class in the parent class?
I understand how it could go the other way around, since the child has all the variables/methods of the parent class, so when you initialize them you are just initializing the variables specified in the parent constructor, that exist by definition in the child. The problem is, when you go the other way around, it is not necessarily true. A child can have variables the parent doesn't, so how is it possible to use the child constructor with the parent, when the parent does not even have the variables in the first place?
What uses does this feature have in development? I would think that if you want an instance of class B, you would declare it as B thing=new B(), and not A thing=new B(). This is probably my inexperience talking, so I would appreciate enlightenment on why and how a parent class can be initialized as one of its children.
Why is it possible to use the constructor of a child class in the
parent class?
This is not correct. When you do
Object obj = new MyClass();
Object obj; declares a reference of the type Object
and new MyClass(); returns a reference to the object it created.
So, you are instantiating a MyClass and assigning the reference to the object created to a reference of the type Object, and this is possible because MyClass is an Object.
As you say,
A child can have variables the parent doesn't
That's called extending the parent functionality (inheritance).
For your second question think about the classic Animal example: Suppose you create a Animal class and you create a method makeSound() on it.
Now you create two subclasses of Animal, Dog and Cat, that overrides the makeSound()method of Animal (a Dog barks and a Cat meows).
Imagine that you represent a room full of Animals (Dogs and Cats) using a List, and you want to make all of them makeSound(). Your list will be declared as List<Animal> because you don't know the kind of Animals that you will store.
And then you iterate over the List to call makeSound() for each Animal. It doesn't matter if the Animal is a Dogor a Cat, it will make it's sound.
And then imagine you want to add Birds to the List. Easy, isn't it?
You are thinking in terms of C++ semantics, but this is Java. In Java, all non-primitive type variables are references, not instances.
In C++, when you say
Object obj;
you allocate a new Object instance on stack or in static memory.
When you say
Object obj = new MyObject;
you invoke a constructor of Object class that takes MyObject pointer (or may be something else that MyObject can be converted to).
In Java,
Object obj;
does not create any instances of Object. It simply creates a variable that can have a reference to an Object instance, but at the moment does not refer to any. It is initialized to null.
Object obj = new MyObject();
allocates an instance of MyObject. It does not allocate a new instance of Object. It simply sets the variable to refer to the new instance. In C++ terms this is much more similar to
Object *obj = new MyObject();
So we're not constructing a parent instance from child instance. We're changing a value the variable is set to, from null to a new child instance.
First, you must get a clear understanding of things. Your example expression:
Object obj = new MyClass(); is actually a compound of two elementary operations.
The first one is creating an instance of MyClass: new MyClass(). The new keyword is basically the only way of actually obtaining an instance of a class (lets ignore runtime reflection to keep this simple), and you are literally naming what you want to create (MyClass) here by its constructor. There is no way to create anything other than what you literally named with the new keyword. The result of new is (implicitly) an instance of MyClass, but the explicit result of a new X is a reference of type X (the reference referring to the newly created instance).
Now the second operation is assigning the reference to your (new) MyObject to another reference of type Object. And this is valid because MyObject is an Object (due to inheritance).
Why would you need this?
This is an essential feature to actually make use of polymorphism. The ability to refer to any child class as its superclass is what makes polymorphism so powerful. You basically will use it everywhere where there is an aspect common to two classes, but there are also differences.
A real world example would be graphical user interfaces. There are buttons, lists, tables and panels in a window, which are all user interface elements, but each does a different thing. To present them neatly organized in a window, these elements are often nested into panels, more abstractly said into containers. Now a container doesn't care what kind of elements go into it, as long as they are components. But to handle them properly a container does need some basic information about these components, mostly how much space they occupy and how to actually draw them. So this is modelled as something like:
public abstract class Component {
public int getWidth() { ... }
public int getHeight() { ... }
public void paint(Graphics g) { ... }
}
public class Container extends Component {
public void add(Component child) { ... }
public void paint(Graphics g) {
for (Component child : children) {
child.paint(g);
}
}
}
Thats almost straight lifted out of the JDK, the point is, if you needed to refer to each Component as its concrete type, it would be impractical to build a Container, it would need extra code for each Component you decide to make (e.g. there would be an addButton, addTable and so on). So instead, Container just works with reference to Component. No matter what Component is created (e.g. Button, CheckBox, RadioButton etc.), since Container just relies on them to all be Component's, it can handle them.
Every class in Java is descended from Object. So MyClass is an Object, by definition, but a more specialized version of it. Think of it like this: every living creature is an Animal. A Cat is a special kind of animal; a specific type. Since the Cat is an Animal, you can still just call it an Animal:
Animal a = new Cat();
But doing so, with a, you can't do anything specific to a Cat, like meow() or purr(), but you can call methods which are valid for all Animals, such as breathe().
HTH
class myMobile{
public void call{
System.out.println("Mobile");
}
}
public class mainClass{
public static void main(){
Object o=new myMobile();
//here we can call methods which are common to all
// objects not specific to
// myMobile object
}
}
Because a MyClass is a Object. Note that java is special because Object is the superclass of every other class type (there is no equivalent in C++).
A more interesting example would be if you had a class or interface and one or more subclasses. This comes up all the time in OOD. Consider for example java's jdbc API: a common set of interfaces to connect and query a database that can be implemented by different concrete classes. You only need to code to the API and then at runtime use the implementation for your DB of choice.
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
i.e. every Java class is an Object. This is why.
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.
You have two separate things here:
The construction of a new instance
The assignment of that instance to
a variable
Since your instance of MyClass is also an instance of Object, this works well.
Consider the following, generic situation:
class A extends B implements C,D {
}
As your A is a B and also a C and a D and an Object, once you created an instance, you can (directly or indirectly) assign it to variables of all those types:
A a = new A();
B b = a;
C c = a;
D d = a;
Object o = a;
Your view on the fields or methods is limited by the type of the variable (i.E. as variable of type C, you only see the methods declared by C).
Nevertheless, your instance is always of the type you instanciated using the constructor, regardless of the variable type.

Java interfaces and types

Let's say you have some Java code as follows:
public class Base{
public void m(int x){
// code
}
}
and then a subclass Derived, which extends Base as follows:
public class Derived extends Base{
public void m(int x){ //this is overriding
// code
}
public void m(double x){ //this is overloading
// code
}
}
and then you have some declarations as follows:
Base b = new Base();
Base d = new Derived();
Derived e = new Derived();
b.m(5); //works
d.m(6); //works
d.m(7.0); //does not compile
e.m(8.0); //works
For the one that does not compile, I understand that you are passing in a double into Base's version of the m method, but what I do not understand is... what is the point of ever having a declaration like "Base b = new Derived();" ?
It seems like a good way to run into all kinds of casting problems, and if you want to use a Derived object, why not just go for a declaration like for "e"?
Also, I'm a bit confused as to the meaning of the word "type" as it is used in Java. The way I learned it earlier this summer was, every object has one class, which corresponds to the name of the class following "new" when you instantiate an object, but an object can have as many types as it wants. For example, "e" has type Base, Derived, (and Object ;) ) but its class is Derived. Is this correct?
Also, if Derived implemented an interface called CanDoMath (while still extending Base), is it correct to say that it has type "CanDoMath" as well as Base, Derived, and Object?
I often write functions in the following form:
public Collection<MyObject> foo() {}
public void bar(Collection<MyObject> stuff){}
I could just as easily have made it ArrayList in both instances, however what happens if I later decide to make the representation a Set? The answer is I have a lot of refactoring to do since I changed my method contract. However, if I leave it as Collection I can seamlessly change from ArrayList to HashSet at will. Using the example of ArrayList it has the following types:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
There are a number of cases where confining yourself to a particular (sub)class is not desired, such as the case you have where e.m(8.0);. Suppose, for example, you have a method called move that moves an object in the coordinate graph of a program. However, at the time you write the method you may have both cartesian and radial graphs, handled by different classes.
If you rely on knowing what the sub-class is, you force yourself into a position wherein higher levels of code must know about lower levels of code, when really they just want to rely on the fact that a particular method with a particular signature exists. There are lots of good examples:
Wanting to apply a query to a database while being agnostic to how the connection is made.
Wanting to authenticate a user, without having to know ahead of time the strategy being used.
Wanting to encrypt information, without needing to rip out a bunch of code when a better encryption technique comes along.
In these situations, you simply want to ensure the object has a particular type, which guarantees that particular method signatures are available. In this way your example is contrived; you're asking why not just use a class that has a method wherein a double is the signature's parameter, instead of a class where that isn't available. (Simply put; you can't use a class that doesn't have the available method.)
There is another reason as well. Consider:
class Base {
public void Blah() {
//code
}
}
class Extended extends Base {
private int SuperSensitiveVariable;
public setSuperSensistiveVariable(int value) {
this.SuperSensistiveVariable = value;
}
public void Blah() {
//code
}
}
//elsewhere
Base b = new Extended();
Extended e = new Extended();
Note that in the b case, I do not have access to the method set() and thus can't muck up the super sensitive variable accidentally. I can only do that in the e case. This helps make sure those things are only done in the right place.
Your definition of type is good, as is your understanding of what types a particular object would have.
What is the point of having Base b = new Derived();?
The point of this is using polymorphism to change your implementation. For example, someone might do:
List<String> strings = new LinkedList<String>();
If they do some profiling and find that the most common operation on this list is inefficient for the type of list, they can swap it out for an ArrayList. In this way you get flexibility.
if you want to use a Derived object
If you need the methods on the derived object, then you would use the derived object. Have a look at the BufferedInputStream class - you use this not because of its internal implementation but because it wraps an InputStream and provides convenience methods.
Also, I'm a bit confused as to the meaning of the word "type" as it is used in Java.
It sounds like your teacher is referring to Interfaces and Classes as "types". This is a reasonable abstraction, as a class that implement an interface and extends a class can be referred to in 3 ways, i.e.
public class Foo extends AbstractFoo implements Comparable<Foo>
// Usage
Comparable<Foo> comparable = new Foo();
AbstractFoo abstractFoo = new Foo();
Foo foo = new Foo();
An example of the types being used in different contexts:
new ArrayList<Comparable>().Add(new Foo()); // Foo can be in a collection of Comparable
new ArrayList<AbstractFoo>().Add(new Foo()); // Also in an AbstractFoo collection
This is one of the classic problems on object oriented designs. When something like this happens, it usually means the design can be improved; there is almost always a somewhat elegant solution to these problems....
For example, why dont you pull the m that takes a double up into the base class?
With respect to your second question, an object can have more than one type, because Interfaces are also types, and classes can implement more than one interface.

Java downcasting and is-A has-A relationship

HI,
I have a down casting question, I am a bit rusty in this area.
I have 2 clasess like this:
class A{ int i; String j ; //Getters and setters}
class B extends A{ String k; //getter and setter}
I have a method like this, in a Utility helper class:
public static A converts(C c){}
Where C are objects that are retireved from the database and then converted.
The problem is I want to call the above method by passing in a 'C' and getting back B.
So I tried this:
B bClasss = (B) Utility.converts(c);
So even though the above method returns A I tried to downcast it to B, but I get a runtime ClassCastException.
Is there really no way around this? DO I have to write a separate converts() method which returns a B class type?
If I declare my class B like:
class B { String k; A a;} // So instead of extending A it has-a A, getter and setters also
then I can call my existing method like this:
b.setA(Utility.converts(c) );
This way I can reuse the existing method, even though the extends relationship makes more sense. What should I do? Any help much appreciated. Thanks.
The cast from type A to type B:
B bClasss = (B) Utility.converts(c);
doesn't work because objects of type A don't have all the methods that might be called from references of type B. What would you expect to happen if you called
bClasss.getK();
on the next line? The underlying object has no member variable k, so this cast is not allowed.
You can use references of the higher types in your class hierarchy to refer to objects of lower types, but not the other way around.
Without knowing more, I think the best thing to do is implement multiple methods
A aObj = Utility.convertToA(c);
B bObj = Utility.convertToB(c);
If B extends A, then you should still benefit from some code reuse in the constructors of your classes.
What's important here is what Utility.converts() actually returns - if it doesn't create a new B object and return it, there's no way to get a B from it.
(since you're getting ClassCastException, then it doesn't create B inside)
You should work in the appropriate level of abstraction and write your method signatures to do the same. If the public/default interface of B is modified that heavily from A, then your method signature really should be returning a B. Otherwise, ditch trying to cast it, assign the result of .converts to a variable of type A, and treat it like an A even though it's true type is really a B. You would be defeating the point of abstracting through inheritance if you are trying to downcast here.
Without seeing your source code, I have no clue whether or not it makes sense to use composition in lieu of inheritance here. The above paragraph assumes what you say about "extends relationship makes more sense" is really true.
If your converts() method doesn't actually return a B, then there is no way to cast it to a B. Since you are getting a ClassCastException it clearly doesn't return a B.
You can of course write a converts(C c) that returns a B. But an alternative approach might be to write a constructor:
B(A a)
which creates a B based on the contents of A. Then you use converts to get a C, and create a B from it.

Factory configured by a. object's class - how to do it nicely?

In my current project we have a couple of data classes that deal with core concepts of our application domain. Now at some places in our project we have to have different behavior depending on the concrete object in hand. E.g. a JList has the task to render a list of objects but we want the rendering to be slightly different, depending on the object's class. E.g. an object of class A should be rendered different than one of class B and class C is a totally different animal, too.
We encapsulate the behavior in strategy classes and then have a factory that returns a class suitable for the object that is to be rendered. From the client perspective, that is okay, I guess.
Now from the perspective of the factory this gets pretty ugly, because all we could come up with so far is stuff like
if (obj instanceof classA) return strategyA;
else if (obj instanceof classB) return strategyB;
...
Now, for a pool of already instantiated objects, a map would also work. But if the factory has to actually create a new object, we'd have to put another layer of factory/strategy objects into that map that then return a suitable strategies for displaying.
Is there any design pattern that deals nicely with this kind of problem?
One way to do this is to delegate the implementation to the object itself. For instance, if classes A, B, and C are all rendered differently, you might have them each implement an interface such as:
interface IRenderable {
public void render();
}
Then, each one would provide its own implementation of render(). To render a List of IRenderable, you would only need to iterate over its members and call the render() method of each.
Using this approach, you never have to explicitly check the type of an object. This is particularly useful if any of your classes are ever subclassed. Suppose you had class classD which extends classA, and was to be rendered differently from A. Now code like:
if (obj instanceof classA) return strategyA;
...
else if (obj instanceof classD) return strategyD;
will fail - you would always need to check in order of most to least specific. Better not to have to think about such things.
Edit: in response to your comment - if your goal is to keep the front end code out of the model objects, but you still want to avoid explicit checks, you can use the visitor pattern.
Something like this:
class Renderer {
public void visit(classA obj);
public void visit(classB obj);
// etc
}
and
class classA {
public void accept(Renderer r) {
r.visit(this);
}
}
Now, all the rendering code goes into the Renderer, and the model objects choose which method to call.
Instead of the if/else block you can have a Factory interface, like this
interface RendererFactory {
supports(Object obj);
createRenderer(Object obj);
}
Then you can have an implementation which asks a list of other implementations if one of them support a given type. The other implementations may do an instanceof check in the supports method.
The consumer of the renderer only needs to call createRenderer.
Advantage: Configuration of your RendererFactories possible
Disadvantage: You have to take care about the order of the RendererFactories (but you have to do that with if/else too)
I like the factory-serving-strategy objects a lot. But I wonder if you could treat it like IoC and register strategies for specifci types? You don't have a bunch of if-else's but you would have to 'register' them. But it might also be nice for testing - rather an implementing a 'mock factory' you'd register 'mock strategies'?
You can have your model classes implement an interface like:
public interface RenderingStrategyProvider {
public RenderingStrategy getRenderingStrategy();
}
and return an instance of the appropriate strategy. Like:
public ClassA implements RenderingStrategyProvider {
public RenderingStrategy getRenderingStrategy() {
return new ClassARenderingStrategy(this);
// or without this, depending on your other code
}
}
In that case you wouldn't even need a factory. Or if you want such, it will contain just a one method call. That way you don't have the presentation logic inside your model classes.
Alternatively, you can use convention + reflection, but this is a weird. The strategy for a model class would be ModelClassStrategy, and you can have:
public RenderingStrategy createRenderingStrategy(Object modelObject) {
return (RenderingStrategy) Class.forName(
modelObject.getClass().getName() + "Strategy").newInstance();
}

Categories