Cast Object[] to another type - java

I have class A and class B, where class B requires only 5 of 10 properties from A.
So i have something like,
A[] objArray = populateResponse();
And to cast it into B , i do something like
for (A : objArray ){
// getters here and push it to B obj array manually
}
Any other suggestions to do it in a better way since A has many fields and size of the array can grow large ?
Thanks in advance !

If B extends or implements A, just cast away.
Otherwise - you can't do that. You will get a ClassCastException.
If the two classes are not related and you still want to do that, you should make them related. Create an interface they will both implement and pass around references to that interface. This will still not allow you to cast A to B, though.
If you're worried about too many instances of A, you can convert them to B. Write a function that takes an instance of A and creates an instance of B from it, and lose the A instance.

Related

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

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;

Java: new, inheritance and objects number

I am trying to understand how inheritance is realized inside JVM. It seems to me, that if we have the following code:
class A {
int aa;
}
class B extends A{
int bb;
}
....
B b=new B();
Inside the JVM three objects will be created:
object of B (with field int bb),
object of A (with field int aa)
object of Object.
Of course the programmers see only one object of class B. Am I right? Or is only one object created inside JVM?
What I think:
The new returns the reference to B. Why I think so is (for example) that if we override some method from A in B we can always get it using super. Besides in default constructor B the first line will be call to default constructor A in which we can call the constructor on certain object ONLY IF this object exists. Therefore a separate A object exists?
At first, the spec says that the internal structure of objects is not specified, so in theory, a JVM could internally create more than one object, where B contains only fields new to B, and a link to an A object, which contains the fields of A.
It also says something about the Oracle JVM implementation: A class instance contains three pointers. One to a method table, one to some space in heap where the data of the instances fields is, and one the Class object that instance belongs to.
You can conclude from that, that there is only one instance per object created, namely the instance of B. The method table for this instance contains all methods from B, A and Object, as well as the heap space contains all data from fields from B, A (and Object).
Here only one object will create. it is B object. But B object has state and behaviors of A object. As super type of every class is Object class, B object has Object's state and behavior too. Thanks
Classes represent a type of objects, but only instances create real objects. So only one object is created and it corresponds the result merge of class B with class 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.

how to make List of of mutable objects Immuatable

Hi I was asked this interview question that you have list of objects in an immutable class, Is the class really immuatable, what can be modified and how can you prevent it. I gave the below solution.
public final class A{
final List<B> listOfB; // B is mutable
public List<B> getListOfB(){
return Collections.unmodifiableList(this.listOfB);
}
}
now he says even after getting getListOfB() he can change the 'B' instances and wanted me to avoid this also. Then i said.
public List<B> getListOfB(){
List<B> ret;
for(B b: this.listOfB){
ret.add(b.clone()); // basically make a deep copy of 'b' for return list
}
return ret;
}
The interviewer did not respond back anything saying it was right or wrong.
This solution definately works. But is there a better way of doing it, my approach is very clumsy and requires to too much additional memory.
PS: Assume B cannot be made immutable.
Assuming B is an interface or an implementation of the interface A, you could wrap each element of listOfB by using a java.net.Proxy of B or A respectively, which intercepts all modifying calls by throwing an UnsupportedOperationException instead.
More detailed, replace each item of the listOfB with a java.net.Proxy wrapped instance, implementing A. Then whenever someone fetches an item of listOfB, he will obtain the wrapped instance instead. Whenever someone calls a setter on such a wrapped item, intercept the call and throw an UnsupportedOperationException. Hope you have an idea what I mean. It's basically what Collections.unmodifiableXXX() does. If you have knowledge of all methods which may modify the state of an item of listOfB, B does not have to be an POJO. Just make sure that your wrapper replaces all modifying methods by throwing an exception.

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.

Categories