Instantiate subclass from superclass Java - 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;

Related

Accessing child properties from parent type reference in java

When I create a child object with parent reference like this Parent p = new Child();
then basically it is a child object with parent reference and with properties of both parent and child.
Then if it is a child object with parent type reference then why I cannot access child properties with it.
I am trying to do the following thing:
class Parent {
}
class Child extends Parent {
int a = 20;
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.a); //gives compile time error
// question is , p is parent type reference variable , but it is pointing to object of child
// class, then we should be able to access child properties from it, but we cant, why ?
}
You can do it by typecasting the reference to the child type.
class Parent {
}
class Child extends Parent {
int a = 20;
public static void main(String[] args) {
Parent p = new Child();
System.out.println(((Child)p).a);
}
}
It will throw a ClassCastException if p is not an Object of Child Type. So, it is better to check that p is an Object of Child by instanceof operator
if (p instancof Child) {
System.out.println(((Child)p).a);
}
The reason it isn't working is because parent classes don't have access to their childrens properties. You may be creating a Child class, but you assign it to a Parent object. Since Child is inheriting from Parent you are able to cast Child to Parent.
You are basically doing:
Parent p = (Parent) new Child();
In other words, You are creating a Parent object. There is no a attribue in the Parent class.
You can do:
class Parent{
int a = 20;
}
class Child extends Parent{
public static void main(String[] args){
Child c = new Child();
System.out.println(c.a); //gives compile time error
// question is , p is parent type reference variable , but it is pointing to object of child
// class, then we should be able to access child properties from it, but we cant, why ?
}
Here when you write Parent p = new Child(), then object of child class is created with properties of both Parent and Child class but the reference variable which is used to hold this object is of Parent type or you can say of Parent class.
When we want to access the instance methods or variables of any class, then the reference variable should be of that class only or its child class.
So we cannot access variable of child class with the reference variable of parent class.
Only the variables present in the Parent class can be accessed through the reference variable of parent class, doesn't matter you are using that reference variable to hold parent Class object or Child class object.
So only way to access 'a' instance variable in the code from p reference variable is to typecast p to Child type and then it can access variables of Child class.
`
Parent p = new Child();
System.out.println(((Child)p).a);
`
Here is all possible combination
There is difference at runtime while access member variable and member method
class Parent {
String s = "parent class variable ";
public void display()
{
System.out.println("Parent class method");
}
}
class Child extends Parent{
String s = "child class variable ";
public void display()
{
System.out.println("Child class method");
}
public static void main(String[] args) {
Parent p = new Parent();
Parent c = new Child();
Child cc = new Child();
System.out.println(p.s);
System.out.println(c.s);
System.out.println(cc.s);
p.display();
c.display();
cc.display();
}
}
Output :
parent class variable
parent class variable
child class variable
Parent class method
Child class method
Child class method

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();
}
}

In .NET, does a parent class' constructor call its child class' constructor first thing?

public class Parent
{
Child child1;
public Parent()
{
child1.Name = "abc";
}
...
}
Gets a NullReferenceException. I thought the Parent() constructor calls the Child() constructor first, so that it is possible to access child1 object later in the Parent() constructor???
You need to create an instance of the child; either initialize it as you define it:
Child child1 = new Child();
Or in the Parent constructor:
public Parent(){
child1 = new Child();
child1.Name = "Andrew";
}
The parent class's constructor doesn't call constructors for its members. When the member is a reference, it's just set to null. You need to explicitly allocate it by calling child1 = new Child
Members are not implicitly constructed. They're initialized with their default values (i.e. null for reference type members), which is why your child1 member is null.
You need to create an instance of child1:
public Parent
{
child1 = new Child();
}
On a sidenote, I think you are being confused by constructor call rules for inherited classes. If your Child class inherited your Parent class, the Parent class' default (i.e. parameterless) constructor would be implicitly called (if it existed):
class Parent
{
protected string member;
public Parent()
{
member = "foo";
}
}
class Child : Parent
{
public Child()
{
// member is foo here; Parent() is implicitly called
}
}

Java type casting for hibernate

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
}
}

Categories

Resources