The basis of Java, the difference between abstract classes and interfaces ......
If you cannot clearly tell the difference between the two, you are advised to write it yourself.Code, You will understand.
1. abstract class
Public abstract class testabstractclass {// abstract class can have private methods or private variables: Private int test_num; public abstract int testmethod (); Public int test2method () {return 0 ;} // Private method private int test3method () {return 0 ;}}
2. Interface
Public interface testinterface {// The interface is public and cannot contain private methods or variables. It is public abstract int testinterface (); Public int test2interface ();}
3. Subclass inherits abstract classes
Public class testextendsabstractclass extends testabstractclass {// The method that can be used to override an abstract class. However, the abstract method must implement @ overridepublic int testmethod () {// todo auto-generated method stubreturn 0 ;}}
4. Subclass implementation Interface
Public class testimplementsinterface implements testinterface {// all methods defined by the interface must be implemented @ overridepublic int testinterface () {// todo auto-generated method stubreturn 0 ;} @ overridepublic int test2interface () {// todo auto-generated method stubreturn 0 ;}}
Note: The above code is compiled
Summary:
1. The interface is public and cannot contain private methods or variables, which are used by others. abstract classes can have private methods or private variables;
2. To implement an interface, you must implement all the methods defined by the interface. inheriting the abstract class can have the method required for selection rewriting, but the abstract method must be implemented;
3. In general applications, the top-level interfaces are the interfaces implemented by abstract classes, and finally the implementation of specific classes.
4. multi-interface implementation, class ticket inheritance
Frequently Asked Questions:
1. What is the role of private methods or private variables in abstract classes;
2. What are the differences between Abstract methods and general methods in interfaces;
3. Others ......