Java type casting for hibernate - java

Yes, I know we can upcast or downcast in Java. But the type of the instance doesn't really seems to be change and it's giving me a problem.
E.g.
class Foo{
int a, b;
.. constructors, getters and setters
}
class FooDTO extends Foo {
...
}
FooDTO dto = FooDTO(1,2);
Foo parent = (Foo) dto;
in hibernate, when saving the "parent", it's still think that it's a DTO object and can't be saved. Can I really turn a child instance into a parent instance?

you can save the 'parent' by using hibernate's save(entityName, object) method. In this case the entityName is the fully qualified class name of 'parent'.

No u can't trun child into parent in this way. You have create the object for parent sperately.like,
Foo parent new Foo(dto.getA(),dto.getB());

An object's type cannot be changed after it has been created. If you create a FooDTO object it will always be a FooDTO object.
When you cast you are telling the JVM that you are going to use a reference of type X to point at an object that you know is of type X.
class Parent {}
class Child extends Parent {}
class Test {
public void stuff() {
Parent p = new Parent(); // Parent reference, Parent object
Parent p2 = new Child(); // Parent reference, Child object
Child c = new Child(); // Child reference, Child object
Parent p2 = c; // no explicit cast required as you are up-casting
Child c2 = (Child)p; // explicit cast required as you are down-casting. Throws ClassCastException as p does not point at a Child object
Child c3 = (Child)p2; // explicit cast required as you are down-casting. Runs fine as p2 is pointong at a Child object
String s1 = (String)p; // Does not compile as the compiler knows there is no way a Parent reference could be pointing at a String object
}
}

Related

Inheritance Example in java

In the example below :
class Parent{
void fun() {
System.out.println("Parent class");
}
}
class Child extends Parent{
}
public class Main {
public static void main(String[] ar) {
Child ch = new Child();
ch.fun();
}
}
inheritance example,while instantiating object,we can create an object as Parent ch = new Child(); which is valid but why can't we have something like this Child ch = new Parent();
Thanks in advance.
Child ch = new Parent() is invalid because not every Parent is a Child.
Suppose you had a third class:
class AnotherChild extends Parent {int age = 2;}
The following would also be valid:
Parent otherChild = new AnotherChild();
If Cild child = new Parent() were to be made valid, then for the same reason
Child child = new AnotherChild()
Would also have to be made valid because AnotherChild is a Parent.
Now clearly, that is problematic, because Child is different from AnotherChild.
This example is chosen to make it obvious, but even a simple Parent object (new Parent()) is not a Child instance, because it wasn't instantiated with the Child class or any of its sub-classes.
All this is compile-time type checks, which ensures code safety and object/variable compatibility. One can use allowed casts to go around the problem, but if runtime objects are in fact of incompatible types, the execution would still fail.
In your example you have class Child extends Parent{. This means that a Child is a Parent but Parent is not a Child. Parent is the more generic parent class (Ironic) and Child is the more specific sub class. So you can do something like this:
Parent ch = new Child();
Because you are declaring the generic Parent object, and then instantiating it as a Child object. However you cannot do:
Child ch = new Parent();
Because you cannot declare it as the more specific Child object and then instantiate it as the less specific Parent object

How to access members of child class by using reference of parent class?

Let there are classes:
class Parent {
public Parent getParent() {
...
}
}
class Child extends Parent{
public Parent getChild() {
...
}
}
//instantiating Child by using reference of Parent
Parent parent = new Child();
when I use:
//Works fine
Parent parentObject = parent.getParent();
When I use:
//Doesn't works
Child childObject = parent.getChild();
But when type cast object:
//Works fine
Child childObejct = ((Child)parent).getChild();
being as programmer this is something hectic to type cast explicitly for every call where I wanted to use child members by reference of parent class.
You declared a variable of type Parent named parent that is actually a Child.
If you don't cast the variable you can use only the methods of class Parent.
If you cast the variable to the real type (that in this case is Child) you can access to all the methods of class Child and its super class Parent too.
Note: to have less misunderstandings it is better to name the variable child also if you assign it to the type Parent, so it is clear that this is a real Child.
It is not so complicated. When you have an up-cast, it is simple for the compiler to determine the real type and do the cast because you know every class is simply extended from one parent.
But when you are down-casting an object, compiler can not infer that an object with a Parent reference is which Child object in the runtime because every Parent class can have multiple Child class.
Good Luck.
You would do something like this? I did not understand what you want...
abstract class Parent {
public Parent(){
}
public abstract void doStuff();
}
class Child extends Parent{
public Child() {
super();
}
#Override
public void doStuff() {
// TODO Auto-generated method stub
}
In the main do this
Child c = new Child();
c.doStuff();
//Doesn't works
// parent.getChild() returning Parent object and you are trying to assign to child object, which is not possible implicitly.
Child childObject = parent.getChild();
You can try some more cases by changing as below too:
class Parent {
public Parent getParent() {
return new Parent();
}
}
class Child extends Parent{
public Child getChild() {
return new Child();
}
// to access methods of child class using Parent class,
//You should Override(same method Names and signatures) the methods of Parent Class
public Parent getParent() {
return new Parent();
}
}

Why am I able to access child methods in the parent class?

I have a problem with the understanding of inheritance in Java: I am able to access overwritten methods of the child class when I cast it back to the parent class.
As an Example there are given the two following classes:
The parent one:
public class Parent {
public void whatAreYou() {
System.out.println("parent");
}
}
And a child class:
public class Child extends Parent {
#Override
public void whatAreYou() {
System.out.println("child");
}
public void onlyChildrenCanDoThis() {
//...
}
}
When I now do the following:
Child c = new Child();
Parent p = c;
p.whatAreYou();
I get this output:
child
This is very strange for my understanding of inheritance in Java. I would expect to get a parent output, because I narrowed the child class to the parent class, and with that I should just have access to variables and methods of the parent class.
This is working with p.onlyChildrenCanDoThis(), as I cannot access it, because it is not implemented in the parent class...
...but with overwritten methods Java is not behaving that way! Why is that?
What you are dealing with here is polymorphism. c is instantiated as new child(), and that is why you get child as an output. The fact that p is of type parent doesn't change that fact, it still points to the instance of child.
Here's what you have done
child c = new child();
You created Object of Child class and assigned its reference to c.
parent p = c;
Here you have copied reference of child object to p. Remember the object is still Child's object not parents's object.
p.whatAreYou();
Here you have called whatAreYou method. you are calling this using reference variable p which is pointing to object of child. hence child's method will be called.
Another Interpretation
The output is as it is because of the line parent p = c;
Imagine this:
class Car {
public void whatAreYou() {
System.out.println("Car");
}
}
class Cadillac extends Car {
public void whatAreYou() {
System.out.println("Caddillac");
}
}
If you now say
Cadillac coolCar = new Cadillac();
Car testCar = coolCar;
testCar.whatAreYou();
It becomes pretty obvious that the output is, "Cadillac", no? This is how you can look at inheritence:
Cadillac objects are allways Cars. Car objects can be Cadillacs
Since I explicitly set the Cadillac reference coolCar to point to an object of a Cadillac, and the Car reference testCarto point to the same object, we get the output "Cadillac"
To make it even more obvious, you could even say
Car coolCar = new Cadillac();
Car testCar = coolCar;
testCar.whatAreYou();

Instantiate subclass from superclass Java

I want to try and instantiate a Child object that extends Parent with the properties of a previously instantiated parent object. So something like this:
class Parent {
ClassName property1;
// Setters and getters
}
class Child extends Parent {
public Child(Parent parent) {
this.property1 = parent.getProperty1();
// + other properties
}
}
Parent parent = new Parent();
parent.setProperty1(prop);
Child object = (Child)parent; // Casting exception
Child object2 = new Child(parent); // This is not ideal
Is there any other way to achieve this?
First look up polymorphism. It seems you're not familiar with one of the main features of an OOP language.
Second, you need to instantiate your parent like this
Parent p = new Child();
Child c = (Child) p;

Calling a child's methods where the defined reference type belongs to parent but the actual reference is a child object

I have a parent, and a child class,
class Parent
{
// variables
// constructor
}
class Child extends Parent
{
// variables
// constructor
public void AChildMethod()
{
// do something
}
}
And inside my program, I have a reference of the main type, but it references to a child type
Parent obj = new Child();
Is it possible to call the "AChildMethod" method of the child in a way like this?
obj.AChildMethod();
Thank you very much in advance.
You can check whether it really is an instance of the Child class, and then simply cast to the child type:
if ( obj instanceof Child ) {
((Child) obj).aChildMethod();
// or
Child childObj = (Child) obj;
childObj.aChildMethod();
}
However, if a cast like this is needed, it could be an indication that your class hierarchy should be improved.
If you know that obj is actually a Child, then you can cast it to a Child and then call childMethod. That's the only way to do it.

Categories

Resources