public class Example {
public static void main(String args[]){
Parent p = new Child();
p.m2();
}
}
class Parent{
void m1(){
System.out.println("Parent : m1");
m2();
}
void m2(){
System.out.println("Parent : m2");
}
}
class Child extends Parent{
void m1(){
super.m1();
System.out.println("Child : m1");
}
void m2(){
System.out.println("Child : m2");
m1();
}
}
This Code results in a java.lang.StackOverflowError because when m1() method of the Parent class is invoked, it calls m2() method which is child's m2() method hence results in StackOverflowError.
What should be changed in the Parents m1() method so that it calls Parent's m2() method instead of Child's m2() method?
Do something like this:
class Parent{
void m1(){
System.out.println("Parent : m1");
m2impl();
}
private void m2impl() { /* whatever */ }
void m2(){
m2impl();
}
}
Related
In this below code:
interface I1 {
void m1();
}
interface I2 {
void m2();
}
abstract class A implements I1, I2 {
public void m1() {
System.out.println("Inside A: m1()");
}
}
class B extends A {
public void m1() {
System.out.println("Inside B: m1()");
}
public void m2() {
System.out.println("Inside B: m2()");
}
}
public class Test {
public static void main(String[] args) {
// invoke A's m1()
A a = new B();
a.m1();
}
}
How can I just invoke m1() in A without making any changes to class B i.e. we can't add super.m1() in the m1() in B? With my code I just get the m1() in B because of dynamic method dispatch or runtime polymorphism.
An interviewer asked me this question. And I told him that it wasn't possible to do so but he replied that there is a way but didn't told me how.
As shown below, I tried to cast the object of the sub-class to that of its parent class. That went well. But, when I try to access the overridden method of the parent class, it doesn't happen. Instead the overriding method in the child class is called. I know I can do this using the super keyword, but I just want to know why this can't be done by casting?
This is the parent class:
public class Parent {
public void print() {
System.out.println("In parent");
}
}
This is the child class which has its properties inherited from the parent class:
public class Child extends Parent{
public void print() {
System.out.println("In child");
}
}
This is the class which contains the main method:
public class Main {
public static void main(String[] args) {
Child child = new Child();
((Parent)child).print();
}
}
Clarification
In your example, the object is always Child. Casting is applied only to the reference variable. This casting never impacts the actual object.
Options
As mentioned by others, add a separate method that will call super.() or use hiding. Hiding is not actually overriding.
Beware of the side effects of hiding
public class AccessParent {
public static void main(String[] args) {
Parent p = new Child();
p.methodC();
System.out.println(new String(new char[20]).replace("\0", "-"));
p.methodD();
}
}
class Parent {
void methodA() {
System.out.println("Parent.methodA");
}
private void methodB() {
System.out.println("Parent.methodB");
// this will still call Child.methodA
// a hidden method can not control the scope of overridden method
methodA();
}
void methodC() {
System.out.println("Parent.methodC");
methodB();
}
void methodD() {
System.out.println("Parent.methodD");
// hidden method will be called
// technically Child.methodB() is not overridden
methodB();
}
}
class Child extends Parent {
#Override
void methodA() {
System.out.println("Child.methodA");
}
// this not overridden
void methodB() {
System.out.println("Child.methodB");
}
}
This will output
Parent.methodC
Parent.methodB
Child.methodA
--------------------
Parent.methodD
Parent.methodB
Child.methodA```
You can't access a overriden method directly from a child class. The best you can do is add another function to your child that calls the parent print function.
public class Child extends Parent{
public void print() {
System.out.println("In child");
}
public void printParent() {
super.print()
}
}
Then you can access it like this,
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.printParent();
}
}
Overriding is a principle which gives weightage on inheritance.
If you have a specific requirement to behave as per the casting then the method must be class level "static" instead of instance level.
You would loose the beauty of true inheritance and enter in hiding it more. However, the same can be achieved in casting way
package com.company.language;
public class InheritanceTrial {
public static void main(String[] args) {
Child child = new Child();
child.print();
((Parent)child).print();
}
}
class Parent {
public static void print() {
System.out.println("In parent");
}
}
class Child extends Parent{
public static void print() {
System.out.println("In child");
}
}
With the help of java.lang.invoke.MethodHandles, java.lang.invoke.MethodHandle and java.lang.invoke.MethodType we can only access the immediate parent's method. So this might help your question.
Working solution
public class Child extends Parent {
public static void main(String[] args) throws Throwable {
MethodHandle MH_Parent = MethodHandles.lookup().findSpecial(Parent.class, "print" , MethodType.methodType(void.class), Child.class);
MH_Parent.invokeExact(new Child());
}
public void print() {
System.out.println("In child");
}
}
class Parent {
void print() {
System.out.println("In parent");
}
}
Failing Solution
class Parent {
public void print() {
System.out.println("In parent");
}
}
class Child extends Parent{
public void print() {
System.out.println("In child");
}
}
public class Main {
public static void main(String[] args) throws Throwable {
MethodHandle MH_Parent = MethodHandles.lookup().findSpecial(Parent.class, "print" , MethodType.methodType(void.class), Child.class);
MH_Parent.invokeExact(new Child());
}
}
I have a Shape and Square class:
public class Shape {..}
public class Square extends Shape {...}
I have a Parent and Child Class that have methods to work on Shape/Square:
public class Parent(){
public void doSomething(Shape a){
print("Parent doSomething called");
}
}
public class Child extends Parent(){
#Override
public doSomething(Shape a){
print("Child doSomething for SHAPE called");
}
public doSomething(Square a){
print("Child doSomething for SQUARE called");
}
}
Now, when i execute this:
Shape square = new Square();
Parent parent = new Child();
parent.doSomething(square);
As expected, "Child doSomething for SHAPE called" is the output.
Is there a way to get the "Child doSomething for SQUARE called" output, by pure polymorphism, without defining the doSomething(Square a) in Parent class and use #Override in child?
Needless to say, i am trying to avoid any if/else checks with instance of operator and extra castings.
What you want to do is to let each shape be responsible for printing/returning the message itself and that is :
class Shape {
public String doSomething(){
return "doSomething for SHAPE called";
}
}
class Square extends Shape {
#Override
public String doSomething(){
return "doSomething for SQUARE called";
}
}
Here is your parent and child class :
class Parent{
public void doSomething(Shape a){
System.out.println("Parent doSomething called");
}
}
class Child extends Parent{
#Override
public void doSomething(Shape a){
System.out.println("Child "+a.doSomething());
}
}
Execute :
Shape square = new Square();
Parent parent = new Child();
parent.doSomething(square);
Hope that makes sense.
below works fine
public class PloyM {
public static void main(String[] args) {
Child c = new Child();
c.doSomething(new Shape());
c.doSomething(new Square());
}
}
class Shape { }
class Square extends Shape {}
class Parent {
public void doSomething(Shape a){
System.out.println("Parent doSomething called");
}
}
class Child extends Parent {
#Override
public void doSomething(Shape a){
System.out.println("Child doSomething for SHAPE called");
}
public void doSomething(Square a){
System.out.println("Child doSomething for SQUARE called");
}
}
I want to know whether a child class calling parent method that invokes an overloaded method in the parent class, will invoke the overloaded method in the child class
class Parent {
void doStuff() {
}
void asd() {
doStuff();
}
}
class Child extends Parent {
void doStuff() {
// implementation
}
}
static void main(Args... args) {
new Child().asd(); -> does this invoke the doStuff with the implementation or the empty doStuff in the parent class?
}
class Parent{
void doStuff(){
System.out.println("parent class");
}
void asd(){
doStuff();
}
}
class Child extends Parent(){
#Override
void doStuff(){
//super.asd();
System.out.println("child class");
}
}
/**
* When you run the program you will see the two methods being called
* one from the parent class and then the override method for child.
* just uncomment the super.asd() in childs doStuff() to see both print.
**/
public static void main(String [] args){
Child c = new Child();
c.doStuff(); // call methods
}
I am creating child class object. I know parent class constructor called first .If i want to call parent class print method so I am used this.print() but this is not working.
Please suggest me how to call parent class print() method without creating parent class object.
public class Test
{
public static void main(String[] args)
{
Child Child = new Child();
}
}
class Parent
{
void print()
{
System.out.println("parent class print method");
}
Parent()
{
this.print();
}
}
class Child extends Parent
{
void print()
{
System.out.println("child class print method ");
}
}
in child constructor You can call a super class method like :
super.print();
see java docs
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
To call any parent method use super. This also works for the constructor:
class Child extends Parent
{
void print()
{
System.out.println("child class print method ");
}
Child() {
super.print(); // parent print method
this.print(); // child print method
}
}
"this" keyword refers to current class and "super" keyword refers to its parent class or interface which it extends or implements respectively.
Clear my concept thanks to anwser my question..
public class Test
{
public static void main(String[] args)
{
Child Child = new Child();
}
}
class Parent
{
void print()
{
System.out.println("parent class print method");
}
Parent()
{
this.print();
}
}
class Child extends Parent
{
void print()
{
super.print();
}
}
output:
parent class print method