Java programming ideology Reading Notes 2nd ~ Chapter 7
Chapter 2 interfaces and inner and hidden classes
I. Interface
1. If the class implementing the interface does not implement all functions in the interface, the class must be declared as abstract class, And the unimplemented functions in the interface are abstract class in this class.
- InterfaceInterface {
- Public VoidF ();
- Public VoidG ();
- }
- Abstract ClassFirstImplementsInterface {
- Public VoidF (){}
- }
- ClassSecondExtendsFirst {
- Public VoidG (){}
- }
- Public ClassExplicitStatic {
- Public Static VoidMain (String[] Args ){
- Interface f =NewSecond ();
- F. f ();
- F. g ();
- }
- }
2. All functions in the interface automatically have the public access permission. Therefore, when implementing an interface, all functions inherited from this interface must be defined as public.
- InterfaceMyInterface {
- Public VoidF ();
- VoidG ();
- }
- ClassFirstImplementsMyInterface {
- Public VoidF (){}
- //! Void g () {} error, should be defined as public
- }
3. Data members in the interface automatically become static and final
- InterfaceMyInterface {
- IntI = 5;
- VoidF ();
- VoidG ();
- }
- ClassFirstImplementsMyInterface {
- Public VoidF (){}
- Public VoidG (){}
- }
- Public ClassExplicitStatic {
- Public Static VoidMain (String[] Args ){
- MyInterface x =NewFirst ();
- // The data member I of MyInterface is static and can be called directly
- System. Out. println ("MyInterface. I =" + MyInterface. I + ", x. I =" + x. I );
- // The data member I of MyInterface is final and cannot be modified
- // X. I ++;
- // MyInterface. I ++;
- }
- }
4. Multi-Inheritance
1) devriced class can inherit multiple interfaces and one abstract or concrete base class at the same time. If both base class and interface are inherited, you must first write down the name of the concrete class, and then the name of interfaces.
2) If the representative class inherited by derived class has the same function as interfaces, you can not implement that function in derived class.
- InterfaceCanFight {
- VoidFight ();
- }
- InterfaceCanSwim {
- VoidSwim ();
- }
- ClassActionCharacter {
- Public VoidFight (){}
- }
- ClassHeroExtendsActionCharacter
- ImplementsCanFight, CanSwim {
- Public VoidSwim (){};
- }
- Public ClassExplicitStatic {
- Static VoidF (CanFight x) {x. fight ();}
- Static VoidS (CanSwim x) {x. swim ();}
- Static VoidA (ActionCharacter x) {x. fight ();}
- Static VoidH (Hero x ){
- X. fight (); x. swim ();
- }
- Public Static VoidMain (String[] Args ){
- Hero h =NewHero ();
- F (h); s (h); a (h); h (h );
- }
- }
Because in Actio