I am doing this:
Child child = (Child)parent;
Which gives me an error, I found it isn't possible to do it like this. I don't know exactly why, but I think it should be possible, if Child class inherits from Parent class, it contains the Parent object data.
My questions are:
Why it doesnt work?
How can i make this work, without setting every single parent's
attribute like this
:
class Parent{
public int parameter1;//...
public int parameter1000;
}
class Child extends Parent
{
public Child(Parent parent)
{
this.parameter1 = parent.parameter1;//...
this.parameter1000 = parent.parameter1000;
}
}
Well you could just do :
Parent p = new Child();
// do whatever
Child c = (Child)p;
Or if you have to start with a pure Parent object you could consider having a constructor in your parent class and calling :
class Child{
public Child(Parent p){
super(p);
}
}
class Parent{
public Parent(Args...){
//set params
}
}
Or the composition model :
class Child {
Parent p;
int param1;
int param2;
}
You can directly set the parent in that case.
You can also use Apache Commons BeanUtils to do this. Using its BeanUtils class you have access to a lot of utility methods for populating JavaBeans properties via reflection.
To copy all the common/inherited properties from a parent object to a child class object you can use its static copyProperties() method as:
BeanUtils.copyProperties(parentObj,childObject);
Note however that this is a heavy operation.
change 'this' to 'super' in your child constructor, and remove the parent parameter, instead replace that with the two parameters
int parameter1;//...int parameter1000; :)
class Parent{
public int parameter1;//...
public int parameter1000;
}
class Child extends Parent
{
public Child(int parameter1, int parameter1000)
{
super.parameter1 = parameter1
super.parameter1000 = parameter1000;
}
}
Do you really want to cast you parent into the child class? If the given Object (given as a Parent object) was created as a child class, you can access the correct functions without the cast. Here is an example:
In the main you see a Vector 'ps' to store Parent objects, but added are Child objects which extend from the Parent. While iterateing through that vector, I dont know which kind of child I get next (thus I cannot cast to the correct class), but due to the keyword Override of the function I call, the correct child/method is used.
import java.util.Vector;
import lib.Parent;
import lib.C1;
import lib.C2;
public class MyClass {
public static void main(String []args){
System.out.println("Hello World");
C1 c1 = new C1();
C2 c2 = new C2();
ps.add(c1);
ps.add(c2);
for(int k = 0; k < ps.size(); k++){
ps.get(k).setInteger(); // no cast needed
System.out.println("stored entity " + ps.get(k).i);
}
// or use a ranged for loop
for(Parent p: ps){
p.setInteger();
System.out.println("stored entity " + p.i);
}
}
static Vector<Parent> ps = new Vector<>();
}
The Parent class: The keyword abstract forces every child to implement that method, so if you have a Parent object you can safely call this method. Since the Parent class itself is abstract you wont have an object which is just a Parent object since that is not allowed and wont compile.
package lib;
public abstract class Parent{
public Integer i;
public abstract void setInteger();
}
And here are two Child classes which have an different implementation of the setInteger() method.
package lib;
import lib.Parent;
public class C1 extends Parent{
#Override
public void setInteger(){
i = new Integer(1);
}
}
Second Child:
package lib;
import lib.Parent;
public class C2 extends Parent{
#Override
public void setInteger(){
i = new Integer(2);
}
}
The Output is
stored entity 1
stored entity 2
stored entity 1 <-- ranged for
stored entity 2 <-- ranged for
Edit:
The file structre looks like this
|-MyClass.java
|-lib
|-Parent.java
|-C1.java
|-C2.java
Related
I have parent class and a child class, both of having a method m1 with same signature (Override), can I call parent class method in following scenario. I dont want to change child class method.
// Super class
public class Parent
{
public void m1()
{
System.out.println("Parent method");
}
}
// Sub class
public class Child extends Parent {
#Override
public void m1() {
System.out.println("Child method");
}
}
// User class
public class Kavi {
public static void main(String[] args) {
Parent p = new Child();
p.m1();
}
}
I want to call parent class m1 method. I know that I can use super in child class method to call its parent method. but I have no right to change the source code of child class. and I have to call it from child class object. please anybody help !!! is it possible in java ??
While creating the Object you are using reference of Super class but your object is of child class, so while calling m1() method the overrided method will be invoked. If you want the method of the super class to be invoked then object should be of Super class. As :
Parent parent=new Parent();
parent.m1();
OR
you can invoke the super class m1() method from the child class.
#Override
public void m1() {
super.m1();
System.out.println("Child method");
}
OR ELSE
import java.lang.reflect.*;
class A {
public void method() {
System.out.println("In a");
}
}
class B extends A {
#Override
public void method() {
System.out.println("In b");
}
}
class M {
public static void main( String ... args ) throws Exception {
A b = new B();
b.method();
b.getClass()
.getSuperclass()
.getMethod("method", new Class[]{} )
.invoke( b.getClass().getSuperclass().newInstance() ,new Object[]{} ) ;
}
}
Without changing the code, you can't do this. You're essentially talking about p.super.m1() which isn't legal in Java. If you want your parent to act like a parent, don't make it a child.
If both parent and child are stateless, you could create a facade over them and explicitly manage the state; this would work, but I wouldn't recommend it.
public class Facade extends Parent {
public enum State {PARENT, CHILD};
private final Child delegate;
private State state = State.CHILD;
public Facade(Child delegate) {
this.delegate = delegate;
}
#Override
public void m1() {
if (State.CHILD == state) {
delegate.m1();
} else {
super.m1();
}
}
public void setState(State state) {
this.state = state;
}
}
This is a purely academic exercise - I can't think of a single good reason to do this in the real world. If you're using an OO language, don't fight the OO paradigm!
I think it not possible. There are two ways to call a parent class method
1.) crate object of parent class as
Parent p = new Parent();
2.) Use super in child class method as
#Override
public void m1() {
super.m1();
System.out.println("Child method");
}
Apart from the already mentioned way, you can declare both the methods as static.
so when you do this
Parent p = new Child();
p.m1();
the static method of parent class would be called and the output will be "Parent method"
Note : The static keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves.
So if you have a variable:
private static int i = 0; and you increment it ( i++ ) in one instance, the change will be reflected in all instances.
If you can not use super then instead of creating the child class object you can directly use
Parent p = new Parent();
p.m1();
if you can't even modify the code inside main method then I think it's not possible .
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();
Please help me to understand how inheritance works.
If I have two classes, parent and child. When I create an instance of child is parent class instance constructed as well or not?
My code of Parent class.
public class Parent {
private char s;
#Override
public int hashCode() {
return s;
}
}
And Child
public class Child extends Parent {
private int i;
public Child(int i) {
super();
this.i = i;
}
#Override
public int hashCode() {
return i;
}
}
And finally the test
public class Main {
public static void main(String[] args) {
Child child = new Child(100);
System.out.println(child.hashCode());
System.out.println(child.getClass().getSuperclass().hashCode());
}
}
In output I get
100
2000502626
So the hashes of objects are different. It means that when I create instance of Child it is also created instance of Parent. Am I right?
Your question has nothing to do with inheritance.
the 100 you get from child instance's hashcode() method, as you expected.
The 2000502626 was from Parent.class, not Parent object.
Parent.class has type java.lang.Class
parent object has type Parent
When you create a Child object a Parent constructor is invoked as well, because a Child is a Parent.
But when you do this:
System.out.println(child.getClass().getSuperclass().hashCode());
you're not invoking Parents instance hashode. You are invoking hashCode() of the instance of the Class object.
See what child.getClass().getSuperclass() returns. It returns an instance of type Class not of type Parent/Child.
You cannot invoke Parents instance methods using child.getClass().getSuperClass() - that doesn't return the instance of a type, but an object representing this type.
Try doing this in child method:
#Override
public int hashCode() {
System.out.println("In child hashCode: " + i);
System.out.println("Parents hashCode: " + super.hashCode());
return i;
}
This will return 100 and 0, as Parents s hasn't been initialized.
Actually, there will be just one child object created. Since every child is a parent, the parent constructor will be invoked. if you print this in both child as well as parent instance methods, it will print the same (child object)
check - this question
If I have two classes, parent and child, When I create an instance of child is parent class instance constructed as well or not?
Yes. It works through Constructor. When you call constructor of your child class to create object, it first calls its parent class contructor and hence creates object of parent class
Yes. Both parent and child object are created. The child class constructor calls the parent(super) class constructor first, then only other functions of the child class are performed. As you can see from your own code two different values getting printed.
In java i have a class A which extends class B
I want to assign all of the contents from class B to class A
thing is i want to do it from inside class A now this seems reasonable easy to do just transfer all of the variables.
This is the hard part. I didn't make class B it's a part of android.widget
In c++ you would just take in class b and then assign to *this and cast it.
How would i go about doing this in java?
To further clarify it's a relativelayout i need to copy all the contents of a relativelayout into a class that extends relative layout
class something extends other
{
public something(other a){
//transfer all of the other class into something
this=(something)a; // obviously doesn't work
//*this doesn't exist?
//too many variables to transfer manually
}
}
Thanks so much for all the help. Really appreciate it!!!
See the code given below . It is using java.lang.reflect package to extract out all the fields from super class and assigning the obtained value to the child class variables.
import java.lang.reflect.Field;
class Super
{
public int a ;
public String name;
Super(){}
Super(int a, String name)
{
this.a = a;
this.name = name;
}
}
class Child extends Super
{
public Child(Super other)
{
try{
Class clazz = Super.class;
Field[] fields = clazz.getFields();//Gives all declared public fields and inherited public fields of Super class
for ( Field field : fields )
{
Class type = field.getType();
Object obj = field.get(other);
this.getClass().getField(field.getName()).set(this,obj);
}
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String st[])
{
Super ss = new Super(19,"Michael");
Child ch = new Child(ss);
System.out.println("ch.a="+ch.a+" , ch.name="+ch.name);
}
}
All the variable and function of parent class(not private) is direct access in child class.You don't need to assign any thing in child Class.You can direct access.
This will not work:
Something something = (Something) other.clone();
if the true runtime type of other is Other.
Instead you have to create a copy constructor, or instantiate other as an instance of Something and then clone it.
I have a Parent.java class and 4 child classes as Child1.java, Child2.java and so on.
There are two methods
m1()
m2()
and one field
f1
Field f1 has different values based on the child class.
Method m1 has the common implementation so I have put it in Parent.java class. It also refers method m2.
Method m2 has common implemtation but it process field f1 which is different for all the child classes.
So my questions are as follows:
Q1. Should I place the field f1 in the parent class and let all the child classes inherit them and initialize them in their own constructors or Should I make a field f1 for all the child classes.
Q2. As the method m2 has common implementation but process field f1 which doesn't have same value for every child class, so should I place it in parent class or child class.
Q3. If I should place the method m2 in parent class, the there is one problem that method m1 (which have common implementation) refer method m2, so would it create any problem?
Place m2 and f1 in the parent class if m2's implementation is the same for all classes. If there's a specific part for each child class that can be run after the common part - separate it and place it in the child classes while calling super.m2(). Set f1 in each child class's constructor.
The result will look something like this:
public abstract class parent {
private int field = 0;
public parent(int f) {
field = f;
}
public void m1() { /* m1's implementation */ }
public void m2() { /* m2's common implementation */ }
}
public class child1 {
public child1() {
super(1);
}
#Override
public void m2() { super.m2() /* m2's child1 implementation */ }
}
public class child2 {
public child2() {
super(2);
}
#Override
public void m2() { super.m2() /* m2's child2 implementation */ }
}
This should allow you to push the maximum amount of code as far back in the hierarchy as it can go. Least code duplication.
Edited to fix trying to access a private member from a child class. Changed to setting it using the constructor.
In my opinion:
f1 should be in the parent class and initialized in the child constructor. This way, the get and set methods are only written once.
m2 should be in the parent class.
m1 should be also be in the parent class. Don't forget that you can also make methods abstract if they do not have a common implementation but exist in all child classes. This would allow you to call it from other methods in the parent class despite not being defined there. Also keep in mind that the parent class would also need to be abstract in this case.
From what you described, I don't see any problem with this implementation:
public class Parent {
private int f1;
public Parent(int f1) {
this.f1 = f1;
}
public void m1() { }
public void m2() {
// do something with f1
System.out.println(f1);
}
}
public class Child1 extends Parent {
private final int DEFAULT_FIELD_VALUE = 1;
public Child1() {
super(DEFAULT_FIELD_VALUE);
}
}
public class Child2 extends Parent {
public Child2(int value) {
super(value);
}
}
{...}
What you are trying to do sound like Template Method design pattern: http://en.wikipedia.org/wiki/Template_method_pattern
I suggest putting f1 in the parent class and declaring m2 abstract in the parent class (which will make the class abstract itself).
If the child classes differ only in the value of f1 then there is no point in even creating subclasses, you should just pass f1 in a constructor or use static factory methods to create instances for the different cases. For example:
public class Parent {
private Value f1;
private Parent(Value f1) {
this.f1 = f1;
}
public static Parent makeChild1() {
return new Parent(valueOfF1ForChild1);
}
public static Parent makeChild2() {
return new Parent(valueOfF1ForChild2);
}
}
Also, you might want to check out if an enumeration is suitable for your case.