A few days ago I was asked to pass a formal parameter in the construction method, the parameter is to pass an abstract class reference, since someone asked, it means that there are some people do not understand that this weekend is nothing, just write a blog record, easy to learn!
Abstract classes as formal parameter passing can be constructors, common functions
1: Abstract class passed as formal parameter to constructor
Code embodies
Person.java Testing Abstract Classes
Package Cn.zgz.demo;
public abstract class Person {
public String name;
private int age;
Public person (String name, int age) {
Super ();
THIS.name = name;
This.age = age;
}
public abstract Void Study ();
}
Personinfo.java is an argument-free constructor
public class PersonInfo {
Public PersonInfo (person p) {
}
}
Test.java Test class
public class Test {
public static void Main (string[] args) {
PersonInfo pInfo =new PersonInfo (New person ("condom", 24) {
@Override
public void Study () {
System.out.println ("I Love You");
}
});
}
}
We passed a reference object for the person in the Personinfo constructor, and the person is an abstract class, so it is necessary to implement its study () method, which is used in many places to be more architecturally, Usually the code so write is relatively rare, as for the common method is the same
2: interface passed as formal parameter to constructor
Code embodies
Ilistener.java interface
Package cn.zgz.inter;
/**
* Interface simulates Android button click event
*/
Public interface Ilistener {
void click ();//click Method
}
Package cn.zgz.inter;
Button.java
/**
* button-simulates buttons in Android
* constructor is an interface
*/
public class Button {
Public Button (Ilistener listener) {
Listener.click ();
}
}
Test.java Test class
Package cn.zgz.inter;
/**
* Test class
*/
public class Test {
public static void Main (string[] args) {
Button button = New button (new Ilistener () {
@Override
public void Click () {
System.out.println ("I was clicked");
}
});
}
}
As to whether to pass the abstract class or interface to see the specific business requirements, if you want to pass this parameter not only provide the non-implementation of the method, but also do other initialization work or other callable business methods, then use the abstract class, or use the interface as a formal parameter
JAV abstract class, interface as a usage scenario for formal parameters