当前位置:网站首页>2021-05-12 internal class

2021-05-12 internal class

2022-06-23 10:07:00 Deer like deer

Inner class

Inner class is to define a class within a class

  1. Member inner class
  2. Static inner class
  3. Local inner classes
  4. Anonymous inner class

Member inner class

package oop.demo12;

public class Outer {
    
    private int id=10;
    public void out(){
    
        System.out.println(" This is the method of the outer class ");
    }
    public class Inner{
    
        public void in(){
    
            System.out.println(" This is the method of the inner class ");
        }
        // The inner class accesses the private properties of the outer class 
        public void getID(){
    
            System.out.println(id);
        }
    }
}
// One java There can be more than one class class , But there can only be one public class
package oop.demo12;

public class Application {
    
    public static void main(String[]args){
    
        //new Instantiation 
        Outer outer = new Outer();

        // To instantiate an internal class, you need to instantiate the internal class through the external class of the internal class 
        Outer.Inner inner = outer.new Inner();
        inner.in();

        // The private properties of the external class are accessed through the internal class 
        inner.getID();
    }
}

Static inner class

package oop.demo12;

public class Outer {
    
    private static int id=10;//Inner yes static,id It's going to change to static
    public void out(){
    
        System.out.println(" This is the method of the outer class ");
    }
    public static class Inner{
    
        public void in(){
    
            System.out.println(" This is the method of the inner class ");
        }
        // The inner class accesses the private properties of the outer class 
        public void getID(){
    
            System.out.println(id);
        }
    }
}

Local inner classes

package oop.demo12;

public class Outer {
    

    public void method(){
    
        class Inner{
    // Local inner classes ( It is the same as the local variables in the method )
            public void in(){
    

            }
        }
    }
}

Anonymous inner class

package oop.demo12;

public class Test {
    
    public static void main(String[] args) {
    
        // No name to initialize the class   You don't have to save instances to variables 
        new Apple().eat();
        UserService userService = new UserService(){
    

            @Override
            public void Hello() {
    

            }
        };
    }
}
class Apple{
    
    public void eat(){
    
        System.out.println("1");
    }
}
interface UserService{
    
    public void Hello();
}

原网站

版权声明
本文为[Deer like deer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230954195274.html