Inner class in JAVA-method inner class

The method inner class means that the inner class is defined in the method of the outer class, and the method inner class is only visible inside the method, that is, it can be used only in the method.

Since the inner class of the method cannot be used outside the method of the outer class, the inner class of the method cannot use the access control and static modifiers.

 

 

 

The following example:

 

//外部类
public class HelloWorld {
    
    private String name = "考试课程";
    
    // 外部类中的show方法
    public void show() { 
		// 定义方法内部类
		class MInner {
			int score = 78;
			public int getScore() {
				return score + 10;
			}
		}
        
		// 创建方法内部类的对象
        MInner mi = new MInner();
        
        // 调用内部类的方法
		int newScore = mi.getScore();
        
		System.out.println("姓名:" + name + "\n加分后的成绩:" + newScore);
	}
    
	// 测试方法内部类
	public static void main(String[] args) {
        
		// 创建外部类的对象
        
        HelloWorld mo = new HelloWorld();
        // 调用外部类的方法
		mo.show();
	}
}


operation result:

Name: Exam Course
Score after bonus points: 88

 

Guess you like

Origin blog.csdn.net/liushulin183/article/details/46672895