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
Related
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
}
}
I have a class C1:
public class C1 {
public void method() {
//Do something
}
protected void anotherMethod() {
if (something) {
method();
/*Here, I want to call the method C1.method,
* but C2.method is called
*/
}
}
}
and another class C2 that extends it and overrides the method:
public class C2 extends C1 {
#Override
public void method() {
if (something) {
anotherMethod();
} else {
super.method();
}
}
}
My problem is described in the code comment. I can't run parent method in the parent class. What is the reason?
Annoyingly, you can't (setting aside reflective hacks).
But you could do something on the lines
public class C1 {
public final void _method() /*rename to taste*/{
}
public void method(){
_method();
}
}
and override method in your derived class. If you specifically require the base class method, then call _method(). I think that's the nearest to writing C1::method() which is permissible in C++.
As far as your C2 class is concerned the anotherMethod() is not overriden so it calls its own method() if something is true.
Override it as follows:
#Override
protected void anotherMethod() {
if (something) {
super.method(); //Here, I want to call the method `C1.method`, but `C2.method` is called
}
}
to call the parent method from child's anotherMethod() definition.
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!!!
I wish someone would explain me how this decision was taken. I understand that, the overloaded version is chosen based on the declared type, but why, on the second call, the decision was taken based the runtime type?
public class Test {
public static void main(String[] args) {
Parent polymorphicInstance = new Child();
TestPolymorphicCall tp = new TestPolymorphicCall();
tp.doSomething(polymorphicInstance);
// outputs: Parent: doing something...
call(polymorphicInstance);
// outputs: Child: I'm doing something too
}
public static void call(Parent parent){
parent.doSomething();
}
public static void call(Child child){
child.doSomething();
}
}
public class Parent {
public void doSomething() {
System.out.println("Parent: doing something...");
}
}
public class Child extends Parent{
#Override
public void doSomething() {
System.out.println("Child: I'm doing something too");
}
}
public class TestPolymorphicCall {
public void doSomething(Parent p) {
System.out.println("Parent: doing something...");
}
public void doSomething(Child c) {
System.out.println("Child: doing something...");
}
}
Thanks in advance!
Your Parent class reference is referring to Child class object:
Parent polymorphicInstance = new Child();
So, when you pass the reference in call method, the actual method invoked is the one with Parent parameter type only. But when you call the method doSomething(), on parent reference:
public static void call(Parent parent){
parent.doSomething();
}
It will call doSomething() method, that you have overridden in Child class.
This is the classic case of polymorphism. Suppose you have a class Shape and a subclass Circle, which overrides the method calculateArea() defined in Shape class.
Shape circle = new Circle();
// This will invoke the method in SubClass.
System.out.println(circle.calculateArea());
When you override a super class method in subclass, then the actual method invoked is decided at runtime, based on what actual object your super class reference points to. This is called Dynamic Dispatch of method call.
I want to make an interface and from user point of view i want it to look clean and they can write their code with this syntax.
public class child extends parent {
#Override
public void run() {
}
}
Main is in the parent but how can one call a overriden function in parent.
Also i don't want the name "child" to be mandatory so i can't call it directly.
PS:this is the run function i want to override.
public class parent{
public static void main(String[] args) {
run();
}
}
Make Parent and run abstract. Abstract for a class means that this class cannot be directly instantiated, but can be instantiated if there is a subclass. Abstract for a method means that the method is defined in the abstract class, but is not implemented in the abstract class. Instead subclasses must provide an implementation of the abstract method or declare themselves to be abstract.
public abstract class Super {
public static void main(String[] args) {
Super s = new Sub();
s.main();
}
public abstract void run();
public void main() {
System.out.println("Calling sub class's implementation of run");
// The super class does not know the implementation of run
// but it does know that there must be an implementation to use.
run();
System.out.println("Done!");
}
}
class Sub extends Super {
#Override
public void run() {
System.out.println("sub class implementation of run");
}
}
to call overridden function of perent class use..
super.run();
EX:
public class child extends parent {
#Override
public void run() {
super.run();
}
}
what i get from you is ..u want to call child function from parent class..
For that is seams like a normal class function coz there is only relationship b/w parent-to-child no relation in child-to-parent
So u just make object of child and then call function of child class...
So your main of parent class may be look like this..
public static void main(String[] args) {
new child().run();
}
To call an overwritten function in the parent user something like one of these:
super.run();
((parent) this).run();
Do you mean you want to call the run() function defined in the parent?
public class child extends parent
{
#Override
public void run()
{
super.run(); // call parent's run() function
this.doStuff(); // call child's additional functionality
}
}
You can call super(Parent) class methods using 'super' keyword. Like this.
public class child extends parent {
#Override
public void run() {
super.run();
}
}
I suppose you are confusing between main() function and some random Main class that you are referring to. In general when it comes to inheritance you cannot call a derived class's overridden function from a base class. In that case what you do is create a base class pointer and make it point to derived class object. In that case when you use the base class pointer to invoke the function the overriden derived classs' function gets called.
I am not sure if I answered you entirely..
This might help you.. -> http://www.oodesign.com/dependency-inversion-principle.html
Not sure if i understand correctly. But parent can't know if, where and how it's protected/public methods will be overriden so it cant call the overridden implementations.
If you have to do it, you probably got your class hierarchy design wrong.
You probably need something like this.
public Parent
{
public final void run()
{
this.runChild
}
protected abstract void runChild();
}
public class Child extends Parent
{
public static void main(String[] args)
{
run();
}
protected void runChild()
{
....
}
}
I am not sure whether I am answering your question right. From what I understood is you are trying to do some thing like calling child's run from Parent. If that is the case below is the code snippet to do it.
public abstract class Parent{
public abstract void run();
public void mainMethod(){
//This automatically calls run from child
run();
}
}
And your child implementation is like as shown below.
public class child extends parent {
#Override
public void run() {
//Do the stuff you want to
}
}
public class MainClass{
public static void main(String args[]){
Parent obj = new Child();
// This inturn takes care of the rest.
obj.mainMethod();
//Some other child
obj = new Child2();
obj.mainMethod();
}
}
Hope this helps you.