java子类如何调用父类方法

44次阅读
没有评论

共计 576 个字符,预计需要花费 2 分钟才能阅读完成。

Java 中,子类可以通过 super 关键字来调用父类的方法。

具体步骤如下:

  1. 在子类中创建一个方法,并在方法内部使用 super 关键字调用父类的方法。
  2. 使用 super 关键字后面跟着一个点号(.),然后是要调用的父类方法的名称。
  3. 在调用父类方法的括号中,传入该方法所需的参数。

以下是一个示例代码:

public class ParentClass {public void parentMethod() {System.out.println(" 父类方法 ");
    }
}

public class ChildClass extends ParentClass {public void childMethod() {System.out.println(" 子类方法 ");
        
        // 调用父类的方法
        super.parentMethod();}
}

public class Main {public static void main(String[] args) {ChildClass child = new ChildClass();
        
        // 调用子类的方法
        child.childMethod();}
}

输出结果:

子类方法
父类方法

在上面的示例中,子类 ChildClass 中的 childMethod 方法使用了 super.parentMethod() 来调用父类 ParentClass 中的 parentMethod 方法。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-09发表,共计576字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)