本程序是紧扣之前关于内部类总结的帖子,所总结的一套代码。可参见相关注释,理解相关概念
帖子传送门
代码如下:
- class Cow
- {
- //Cow类的实例变量
- private double height;//奶牛的高度
-
- public Cow(){}
-
- public Cow(double height)
- {
- this.height = height;
- }
-
- //非静态内部类
- private class CowLeg
- {
- //非静态内部类的两个实例变量
- private double height;//奶牛的腿长
- private String color;//奶牛腿的颜色
-
-
- //非静态内部类的两个重载的构造器
- public CowLeg(){}
- public CowLeg(double height,String color)
- {
- this.height = height;
- this.color = color;
- }
-
- //非静态内部类的实例方法
- public void info()
- {
- //直接访问外部类的private修饰的成员变量
- //内部类的height和外部类的height同名;
- //所以需要通过外部类.this来限定
- System.out.println("当前奶牛的腿长:"+ this.height);
- System.out.println("当前奶牛的高度:"+ Cow.this.height);
- }
-
- public String getCowLegColor()
- {
- return this.color;
- }
- }
-
- //静态内部类
- static class CowEyes
- {
- private static int eyeNums = 2;
-
-
- public static int getEyeNums()
- {
- return eyeNums;
- }
- }
-
- public void testLegs()
- {
- CowLeg cl = new CowLeg(1.12,"黑白相同");
- cl.info();
- //访问内部类的实例方法,必须显示创建内部类对象
- //System.out.println("当前奶牛腿的颜色:"+getCowLegColor());
- System.out.println("当前奶牛腿的颜色:"+cl.getCowLegColor());
- }
-
- public static void testEyesNums()
- {
- System.out.println("当前奶牛眼睛个数:"+ new CowEyes().getEyeNums());
- }
- }
- public class myInnerClass
- {
- public static void main(String[] args)
- {
- Cow cow = new Cow(1.5);
- cow.testLegs();
-
- cow.testEyesNums();
-
- }
- }
复制代码 |
|