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... Thanks in advanced.
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”关键字指的是当前类,“ super”关键字指的是其分别扩展或实现的父类或接口。
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.