Write Java programs to practice anonymous internal class applications

Back to this chapter

Return to job list


Statement of needs:

Define an abstract class Bird and create an action class Action that uses an anonymous inner class.

Realization ideas:

Define the abstract class Bird. Define a name attribute of type String, an abstract method fly() whose return type is int, and a getName() method

Define the action class Action, and define an op() method in it. The formal parameter of this method is of type Bird.

In the main() method, instantiate an Action object and call the op() method of the object. The actual parameter of the op() method is an anonymous inner class object that inherits the Bird abstract class. The inner class overrides the getName() and fly() of the Bird class.

Implementation code:

public abstract class Bird {
	private String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }    
    public abstract int fly();
}

public class Action {
    public void op(Bird bird){
           System.out.println(bird.getName() + "能够飞 " + bird.fly() + "米");
    }    
    public static void main(String[] args) {
           Action action = new Action();    	
    	action.op(new Bird() {            
            	      public int fly() {
                	             return 10000;
                         }            
                         public String getName() {
                                return "大雁";
                         }
         });
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_44893902/article/details/106744448