Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcam
7,468 PointsQuestion on Java Inheritance and instantiating a child that has all the properties of the parent
This may be a silly question. The scenario is I have a class called "Parent" and a class called "Child" which inherits from "Parent." If I already have an instance of the parent "Bob" existing, is it possible to create an instance of "Child" with all his properties? Or is the only way to make a new child and reference all the properties of the parent in the constructor? My unsuccessful attempt to cast it is below.
Probably I am thinking about this wrong, would appreciate some input. Thanks!
public class Program {
public static void main(String[] args) {
Parent Bob = new Parent("Bob");
//Bob jumps in a time machine that will turn him into a child which has all the same properties as Bob
Child LittleBob = (Child) Bob;
}
}
public class Parent {
String name;
public Parent(String name) {
this.name = name;
}
public void printName()
{
System.out.println(name);
}
}
public class Child extends Parent {
public Child(String name) {
super(name);
}
public void scream() {
System.out.println("REEEEE!");
}
}