Create Sub-Class Object when Parent Class is initialized - java

is there a way to automatically initialize a subclass when the parent-class is initialized(constructed)?
For example like this:
public class Parent {
public Parent() { //Constructor
...
}
public class Child {
public void foo() {
...
}
}
}
I want to be able to do something like this:
Parent p = new Parent();
p.Child.foo();
Any Ideas? I think it's all about static-ness but I'm not sure, so any help is appreciated. Thanks in advance.

You cannot call it that way.
If the child class must be a non-static class and reside inside a parent class then you will have to initiate it either in the parent class or outside of it before using any of its methods.
You have this option.
public class Parent {
private Child child;
public Child getChild() {
return child;
}
public Parent() { //Constructor
this.child = new Child();
}
public class Child {
public void foo() {
...
}
}
}
After that you can call the foo() method this way.
Parent p = new Parent();
p.getChild().foo();

Maybe somehting like that:
public class Parent {
public Parent() { //Constructor
foo();
}
protected void foo() {
// Do nothing in parent
}
}
public class Child {
#Override
public void foo() {
...
}
}
Edit: this is not a correct anwser as Child does not extend Parent.

Try this code:
This first part is the main. You have to invoke que Parent and make an instance the Child (That is the first lane of the code) After that, you can use the child methods.
Parent child = new Parent().new Child();
child.foo();
On the other hand, the class:
public class Parent {
public Parent(){
}
protected void foo(){
}
public class Child extends Parent{
public Child(){
}
#Override
public void foo(){
System.out.println("I am the child!!");
}
}
}
As you can see that is very similar that you have, but you have to write in the child "extends Parent" to specify the parent of that class.
I hope that could help you!!!

Related

How to access child class method using parent class refrence?

I am getting error while accessing Child class method by using Parent class reference variable.
Please help me.
How can I access that method?
class Parent
{
public void show()
{
System.out.println("Show method in Parent class");
}
}
class Child extends Parent
{
public void print()
{
System.out.println("Print method in Child class");
}
}
public class Downcast
{
public static void main(String args[])
{
Parent p1=new Child();
p1.print();//showing error here
}
}
Your Parent class knows nothing about methods in your Child class. That's why you get error.
One of the possible solutions is to make your Parent class as abstract and add abstract print() method in it, but in this case all subclasses should override this method:
abstract class Parent {
public void show() {
System.out.println("Show method in Parent class");
}
public abstract void print();
}
class Child extends Parent {
#Override
public void print() {
System.out.println("Print method in Child class");
}
}
public class Downcast {
public static void main(String[] args) {
Parent p1 = new Child();
p1.print();
}
}
The error is caused since the Parent class knows nothing about the Child class. One way to fix the error is by doing an explicit cast ((Child) p1).print();
You can do a cast :
class Parent
{
public void show()
{
System.out.println("Show method in Parent class");
}
}
class Child extends Parent
{
public void print()
{
System.out.println("Print method in Child class");
}
}
public class Downcast
{
public static void main(String args[])
{
Parent p1=new Child();
((Child) p1).print();// Out : Print method in Child class
}
}

Call protected method from child

I have a class with method I want to let the execution to child class. Example:
public class Parent {
protected void foo(){return null;}
private void bar(foo());
}
public class Child {
#Override protected void foo(){//do something}
}
and I want to call the foo method of child instead of parent in the bar method. It always calls the parent method.
The foo method can not be abstract...
In the Parent code, if you do:
this.foo();
...then provided the object is a Child instance, it's the Child's foo that will get called. This is an important part of polymorphism. (Assuming, of course, you add extends Parent to the Child declaration.)
Example: (live copy on IDEOne)
class Example
{
public static void main (String[] args)
{
new Child().bar();
}
}
class Parent {
protected void foo() {
System.out.println("Parent#foo");
}
public void bar() {
this.foo();
}
}
class Child extends Parent {
#Override
protected void foo() {
System.out.println("Child#foo");
}
}
Output:
Child#foo

is there any way to call parent class method from child class object in java without modifying methods

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 .

Calling method that exists in child classes but not in parent class

public class Parent {
....
}
public class Child1 extends Parent {
....
public void foo() {
....
}
}
public class Child2 extends Parent {
....
public void foo() {
....
}
}
Here method foo() only exists in the Child classes and CAN NOT be added to the Parent class (not even abstract method). In this situation when I want to call the foo() method on obj which is Parent class's reference then I need to use intanceof with multiple if..else which I want to avoid.
Parent obj = ...// Object of one of the child classes
obj.foo();
EDIT: I Need to use type of obj as Parent only. Else I will not be able to call methods on obj which exists in Parent class.
My Solution: The approach that I am thinking is to define an interface say FooInterface with foo() method and let all the child classes implement it, then I could just type cast the obj to that interface and call foo() method like this:
if(obj instanceof FooInterface){
((FooInterface)obj).foo();
}
Is there a better approach ? Or any improvement to this one?
You can't do it with parent object reference until an unless method is declared in parent class/interface itself.
You have to downcast it to child class because parent class/interface doesn't have any knowledge about the child class other than the contract defined between them.
Here contract means abstract methods.
you can try in this way where there is no need to put a check it.
FooInterface sc =new Child1();
sc.foo();
...
interface FooInterface{
void foo();
}
public class Parent {
}
public class Child1 extends Parent implements FooInterface{
public void foo() {
}
}
public class Child2 extends Parent implements FooInterface{
public void foo() {
}
}
The approach that I am finally taking is to define an interface say FooInterface with foo() method and let all the child classes implement it, then I could just type cast the obj to that interface and call foo() method like this:
Parent obj = ...// Object of one of the child classes
.....
if(obj instanceof FooInterface){
((FooInterface)obj).foo();
}
The polymorphism is applied on object reference, not a type. When you call
FooInterface obj = ...// Object of one of the child classes
obj.foo();
the child class method foo() is called.
If you want to typecast only then there is no need of adding interface. You can typecast it to your desired class and call the method. Example
public class HelloWorld {
public static void main(String args[]) throws FileNotFoundException {
SuperClass sc =new Child1();
if(sc instanceof Child1)//Do same for Child2
((Child1)sc).foo();
}
}
class SuperClass {
}
class Child1 extends SuperClass{
public void foo(){
System.out.println("From child1");
}
}
class Child2 extends SuperClass{
public void foo(){
System.out.println("From child2");
}
}
Output :
From child1
You could implement an AbstractChild inheriting from Parent and then extend this class instead of Parent:
public class Parent {
....
}
public abstract class AbstractChild extends Parent{
public abstract void foo();
}
public class Child1 extends AbstractChild {
....
public void foo() {
....
}
}
public class Child2 extends AbstractChild {
....
public void foo() {
....
}
}
So you need to only check if your instance is instanceof AbstractChild.

Define generic Type of parent class method depending on subclass Type in Java

Is it possible to dynamically identify T as a return type depending on subclass Type?
I want something like the following:
public class Parent {
public <T extends Parent> T foo() {
return (T)this;
}
}
public class Child extends Parent {
public void childMethod() {
System.out.println("childMethod called");
}
}
And then to call:
Child child = new Child();
child.foo().childMethod();
Without defining the type like so:
Child child = new Child();
child.foo().<Child>childMethod(); // compiles fine
Thanks in advance!
You want this:
public class Parent<T extends Parent<T>> {
public T foo() {
return (T)this;
}
}
public class Child extends Parent<Child> {
public void childMethod() {
System.out.println("childMethod called");
}
}
Child child = new Child();
child.foo().childMethod(); // compiles
It is impossible in the Java type system for Parent to refer to the exact class of this. However, it can have a type parameter (say T) that subclasses can specify, as either themselves, or some other type (whatever they want), and use an abstract method to delegate the task of obtaining an instance of a that type T to the subclass.
public abstract class Parent<T> {
// the implementer is responsible for how to get an instance of T
public abstract T getT();
// in this case, foo() is kind of redundant
public T foo() {
return getT();
}
}
public class Child extends Parent<Child> {
public Child getT() {
return this;
}
public void childMethod() {
System.out.println("childMethod called");
}
}
Child child = new Child();
child.foo().childMethod(); // compiles

Categories

Resources