How to call parent class method from it's constructor - java

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

Related

How to access overridden method of parent class without using super()?

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());
}
}

How does the object is initiated in the hierarchy between super class and subordinate class? [duplicate]

This question already has answers here:
Java order of Initialization and Instantiation
(2 answers)
Closed 5 years ago.
I know, there is an implicit super() statement in the constructor of the subordinate class, but how do the class fields, instance fields, and constant fields are initiated and their order in super class and subordinate class, also where are the method information stored?
As demonstrated below, the output of the program is "null", but it will be "child" if I add the static modifier before s in the child class. I suppose that to explain such result, the answer to the questions above is essential.
public class Parent {
private String s = "parent";
public Parent() {
call();
}
public void call() {
System.out.println(s);
}
public static class Child extends Parent {
private /*static*/ String s = "child";
public Child() {
}
public void call() {
System.out.println(s);
}
}
public static void main(String[] args) {
Child child = new Child();
}
}
you can create constructor with parameters like this
in parent class
public Parent(String s) {
this.s = s;
call();
}
and child class constructor
public Child() {
super(this.s);
}
when you are declaring Child Constructor his first line is super()
with default ;
and it is calling Parent class's constructor and Parent class's call method.
you can also do like this
public class Parent {
private String s = "parent";
public Parent(String ss) {
call(ss);
}
public void call(String ss) {
System.out.println(ss);
}
and child class
public static class Child extends Parent {
private String s = "child";
public Child() {
super(this.s);
}
}
public static void main(String[] args) {
Child child = new Child();
}
}
you don't need call() method in child class anymore because you have it in parent class and you can access this method from child class too .

If I invoke a parent's method in parent class, does it invoke child class method with the same name

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
}

could parent object be created using super to call parent method

Would the parent object be created , if we use the super keyword to call the method of the parent class in child object?
Outcomes show that both Mybase and MySub have the same reference address. Not sure whether it is a good demo.
class Mybase {
public void address() {
System.out.println("super:" + this);
System.out.println( this.getClass().getName());
}
}
class MySub extends Mybase {
public void address() {
System.out.println("this:" + this);
System.out.println( this.getClass().getName());
}
public void info() {
System.out.println("this:" + this);
super.address();
}
}
public class SuperTest {
public static void main(String[] args) {
new MySub().info();
}
}
Well, let's find out!
Your test isn't quite going to answer your question. If you want to see if an object is created, why not create a constructor that prints to the console when called?
public class Test {
static class Parent {
Parent() {
System.out.println("Parent constructor called");
}
void method() {
System.out.println("Parent method called");
}
}
static class Child extends Parent {
Child() {
System.out.println("Child constructor called");
}
#Override
void method() {
System.out.println("Child method called");
super.method();
}
}
public static void main(final String[] args) {
new Child().method();
}
}
If you run this, you get this output:
Parent constructor called
Child constructor called
Child method called
Parent method called
So as you can see, when method() was called, no Parent object was created when the super keyword was used. So the answer to your question is "no".
The reason is because super and super() are different. super (no parentheses) is used to access members of the parent class. super() (with parentheses) is a call to the parent constructor, and is only valid inside a constructor as the first call in the constructor. So using super (no parentheses) will not create a new object.
Also, super() doesn't actually create a new, independent Parent object. It just does the initialization work for the fields of Parent that is needed before the child constructor continues.

How to solve the following issue in java?

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();
}
}

Categories