Interfaces in JAVA

/*
 * When the interface is defined, the format characteristics:
 * 1. Common definitions in interfaces: constants, abstract methods
 * 2. The members in the interface have fixed modifiers
 * Constant: public static final
 * method: public abstract
 * Remember: the members of the interface are public
 *
 * Interfaces cannot create objects because there are abstract methods
 * It needs to be implemented by subclasses, and subclasses can only instantiate after subclasses overwrite all abstract methods in the interface.
 * otherwise the subclass is an abstract class
 *
 * The interface can be implemented by multiple classes, and it is also a conversion form that does not support multiple inheritance
 * (Interfaces can be multi-inherited, if the return value of the function with the same name in all parent interfaces is the same)
 *
 * */

interface Inter {
	public static final int NUM = 3;

	public abstract void show();

}

interface InterA{
	public abstract void method();
}

interface A extends InterA{
	
}

class Test1 implements Inter,InterA {
	public void show() {
		System.out.println("123");
	}
	public void method(){}

}

public class InterfaceDemo {
	public static void main(String agrs[]) {
		Test1 t = new Test1();
		System.out.println(t.NUM);
		System.out.println(Test1.NUM);
		System.out.println(Inter.NUM);
	}
}

The above output results are all 3, Test1.NUM and Inter.NUM should be NUM is static, so it can be called directly by the class name

for example:

abstract class Student{
	abstract void study();
	void sleep(){
		System.out.println("sleep");
	}
}

interface Smoking{
	void Smoke();
}

class ZhangSan extends Student5 implements Smoking{
	void study(){}
	public void Smoke(){}
}

class LiSi extends Student5{
	void study(){}
}

public class InterfaceDemo2 {

}

In the above example, students will definitely study and sleep, but not necessarily smoke, so it is not feasible to put smoking directly in the student class, so using the interface, let Zhang San inherit the student class to implement the smoking interface, so that Zhang San can A student again, and a smoker. And Li Sizhi inherits the students and does not realize smoking, then he will not smoke. This definition is more in line with real life.


                                                                                           ---------------------By chick


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325724194&siteId=291194637