黑马程序员——Java基础——内部类

——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-

内部类:就是在类里面定义的类。
1、可以直接访问外部类的成员,包括私有的。
2、外部类要访问内部在类,要建立内部类对象。

public class InnerClassTest {
    public static void main(String[] args){
        Out.In aa=new Out().new In();  //定义一个内部类对象
        aa.inPrint();
    }
}

class Out{
    private int age=10;
    class In{
        void inPrint(){
            System.out.println("外部类的成员变量的值是: "+age);
        }
    }
}

上面的代码 内部类 In 可以访问外部类 Out 的私有成员变量 age

对于外部类成员变量、内部类成员变量和局部变量分别如何访问,从下面的例子可以得知:

public class InnerClassTest2 {
    public static void main(String[] args){
        Out2.In2 bb=new Out2().new In2();
        bb.inPrint();
    }
}
class Out2{
    private int age=100;
    class In2{
        int age=23;
        void inPrint(){
            int age=6;
            System.out.println("局部变量的值: "+age);
            System.out.println("内部类成员变量的值: "+this.age);
            System.out.println("外部类成员变量的值: "+Out2.this.age);
        }
    }
}

当内部类被静态static 修饰时,例子如下:

public class InnerClassTest3 {
    public static void main(String[] args){
        Out3.In3 aa=new Out3.In3();     //静态内部类对象定义方式
        aa.inPrint();
    }
}

class Out3{
    private static int age=10;
    static class In3{    //当内部类被静态static修饰时,上面的外部类成员变量必须也是静态的才能访问
        void inPrint(){
            System.out.println("外部类的成员变量的值是: "+age);
        }
    }
}

如果内部类是私有的,那在主函数中就不能定义内部类对象了,只能通过外部类对象的方法来访问内部类的成员。

下面是例子:

public class InnerClassTest4 {
    public static void main(String[] args){
        Out4 aa=new Out4();     //静态内部类对象定义方式
        aa.OutPrint();
    }
}

class Out4{
    private  int age=10;
    private class In4{   //当内部类被私有化时
        void inPrint(){
            System.out.println("外部类的成员变量的值是: "+age);
        }
    }
    public void OutPrint(){
        new In4().inPrint();
    }
}

匿名内部类:就是内部类的简写格式。一般情况,匿名内部类的建立要有一个前提,内部类必须是继承一个父类或者实现接口。它其实就是匿名子类对象。

public class NiMingClass {
    public static void main(String[] args){
        School aa=new School();
        aa.function();
    }
}

abstract class People4{
    String name;
    abstract void walk();
}

class School{
    String adress;
//  class Student extends People4{
//      int stuId;
//      void walk(){
//          System.out.println("慢慢走的");
//      }
//  }

    void function(){
        //new Student().walk();

        new People4(){
            void walk(){
                System.out.println("慢慢走慢慢走");
            }
            void sleep(){
                System.out.println("睡觉");
            }
        }.walk();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值