您现在的位置是:首页 > 文章详情

Java 内部类创建、调用外部方法

日期:2019-06-05点击:573
  • JDK 1.8.0

创建内部类类对象

Outer outer = new Outer(1L,"fater"); Outer.Inner inner = outer.new Inner(2L,"son");

内部类对象调用外部类方法

  • 内部类与外部类没有重名的方法,可以直接调用外部类方法
  • 内部类与外部类存在重名的方法,必须使用 Outer.this.method() 来进行调用,否则优先调用内部类的方法
public class Outer { private Long id; private String name; public Outer(Long id, String name) { this.id = id; this.name = name; } public void test(){ System.out.println("Outer "+this.id+"--"+this.name); } class Inner{ private Long id; private String name; public Inner(Long id, String name) { this.id = id; this.name = name; } // public void test(){ // System.out.println("Inner "+this.id+"--"+this.name); // System.out.println("my fater is"); // //test(); // 会调用内部类的test()方法,无限循环报错 // Outer.this.test();// 调用外部类方法 // } public void test2(){ System.out.println("Inner "+this.id+"--"+this.name); System.out.println("my fater is"); Outer.this.test(); //test(); // 两种方式皆可,调用外部类方法 } } public static void main(String[] args) { Outer outer = new Outer(1L,"fater"); Outer.Inner inner = outer.new Inner(2L,"son"); inner.test2(); } }
原文链接:https://yq.aliyun.com/articles/704710
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章