Restart learning Java - Abstract classes, interfaces, internal classes

abstract class

Why define abstract methods: If you cannot define a method in terms of its specific implementation details; for example, when you define the eat method of the Person class, you cannot determine its specific implementation details, because Chinese, Western and South Asian people eat differently.This method can be defined as an abstract method, specific The implementation details are left to their descendants (subclasses).

Definition of abstract methods

With the definition of the abstract keyword modifier, the body of the method must be empty (otherwise it is not an abstract method), the abstract method must be non-static (the abstract method cannot be modified by static), and the abstract method cannot be modified by final or private.

[modifier] abstract return value type methodName(); //Note that there is no {}

Definition of abstract class

Why define abstract classes: Classes that define abstract methods must be defined as abstract classes

Definition method of abstract class

[modifier] abstract class className {
	//Modify class definitions with abstract
}

Features of abstract classes

  • Abstract classes cannot be instantiated (constructed but called only by subclasses)
  • Abstract classes can contain attributes, methods, constructs, internal classes, enumerations, code blocks, and so on
  • The methods can be abstract or implemented
  • Classes containing abstract methods must be defined as abstract classes
  • This abstract method may be custom, inherited, or self-interface implemented, otherwise all abstract methods must be implemented
  • In an abstract class, there may be no abstract method

DEMO

/**
* Why abstract classes
* 1,Classes containing abstract methods must be defined as abstract classes;
* However, an abstract class does not have to have an abstract method
* 2,If you expect the current class to not be instantiated,
* Instead, it is left to subclasses to instantiate, defining abstract classes
* (Abstract classes have constructive methods, and abstract classes cannot be instantiated (objects of this class are created directly)
* Person p = new Person(); // FALSE
*/
public abstract class Person {
	// As long as there are curly brackets, you can do it, and that's already done
	/**When a method is defined, its implementation details (what to do and how to do it) cannot be determined.
	* If a method is not native ly modified,
	* When it has no body, this method cannot be executed, and it is an abstract method.
	* Need to use abstract keywords to decorate (abstract)
	*/
	public abstract void eat(String food);
	/**
	* abstract Modifiers cannot be combined with static or final
	*/
}
/**
* Subclass inherits an abstract class
* 1,If the subclass is still unsure of the implementation details of a method (does not implement an abstract method inherited from the parent class),
* Then you can continue to declare this class as an abstract class
* 2,If a subclass does not want to be an abstract class, it must implement an abstract method that inherits from its parent
*/
public class Sinaean extends Person{
	public Sinaean(){
		super();
	}
	// This method is no longer abstract and can have a body of methods
	@Override
	public void eat(String food) {
		System.out.println("Most Chinese eat with chopsticks"+ food);
	}
}
public class Thai extends Person{
	@Override
	public void eat(String food) {
		System.out.println("Thai sometimes eat with their hands: "+ food);
	}
}

/**
* Create an instance of an abstract class:
* 1,Create an instance of its subclass type (this is essential)
* 2,You can get its instances (essentially, or create subclass type objects) statically
*/
public class Main {
	public static void main(String[] args) {
		// Person type cannot be instantiated: abstract classes cannot be instantiated
		// Person p = new Person();//Cannot instantiate the type Person
		// Declare a Person-type variable p (p has a compile-time type of Person)
		// Creates an object of the subclass type of an abstract class and assigns its first address in heap memory to the p variable in stack space
		Person p =new Sinaean();
		p.eat("Hot Pot");
		System.out.println("Runtime type: " + p.getClass());System.out.println("The first address in memory is: "+ System.identityHashCode(p));
		// Creates an object of the subclass type of an abstract class and assigns its first address in heap memory to the p variable in stack space
		// The address previously stored in the p variable will be overwritten
		p = new Thai();
		p.eat("Steamed Rice");
		System.out.println("Runtime type: " + p.getClass());
		System.out.println("The first address in memory is: "+ System.identityHashCode(p));
		Calendar c = Calendar.getInstance(); // Get an instance by static method
		Class<?> clazz = c.getClass();// Gets the real type (runtime type) of the object referenced by c
		System.out.println(clazz);
		Class<?> superClass = clazz.getSuperclass();// Get clazz's parent class
		System.out.println(superClass);
	}
}

summary

Features of abstract classes
 1. Abstract classes [constructed], but cannot be instantiated
	The construction method of an abstract class is exclusively for subclass calls (the construction method can also be executed)
2. Abstract methods may or may not exist in abstract classes
	Classes with abstract methods must be abstract (see the first point in Person)
	There may be no abstract method in an abstract class (see point 2 in Person)
3. How to create an instance of an abstract class: Create an instance of its subclass type (this is the essence)
	Subclass type of object to be created must be non-abstract
	Indirect subclasses do not have to be direct subclasses
	Its instances can be obtained statically (Calendar.getInstance())
	Calendar c = Calendar.getInstance();
4. How should you choose to create an instance of an abstract class?
A>, if there are static methods in the current Abstract class, static methods are preferred
 B>, if there is a static method in the subclass that returns the corresponding instance, use the static method of the subclass
 C>, find non-abstract subclasses, create objects of subclass type
 D>, inherit this class and implement its abstract methods, then create an instance
 Note: Sometimes, in order to fulfill our requirements, we may choose to create subclass objects instead of invoking static methods to get instances

Interface

An interface is a more abstract type than an abstract class; an interface is a specification that is abstracted from several similar classes: it determines Defines the specifications that a batch of classes (implementation classes of interfaces or subclasses of implementation classes) must follow.Interfaces only define constants Or the method, without paying attention to the implementation details of the method, the interface reflects the design philosophy of separation between specification and implementation.

Define interfaces

[modifier] interface InterfaceName {
	Constants defined in interfaces (0 to n)
	Abstract methods defined in interfaces (0 to n)
	static Modification Methods (0 to n)
	Method of default modification (0 to n)
}

Members in interfaces

  • Can contain attributes (constants only)
  • The system appends these modifications to variables that do not explicitly use public static final modifications
  • Can contain methods (must be abstract instance methods)
  • Non-abstract methods are not allowed in interfaces
  • Static methods can exist in interfaces (static methods decorated with static)
  • Default methods can exist in interfaces (methods decorated with default)
  • Can contain internal classes or interfaces
  • Can contain enumeration classes
  • Cannot contain a construction method
  • Cannot contain code blocks

Inheritance and implementation of interfaces

Inheritance of interfaces is implemented using the extends keyword:

public interface Usb1 extends Usb {};

Interfaces in the Java language can inherit multiple interfaces: used between multiple interfaces, separated (comma in English) No.); Subinterfaces can inherit from parent interfaces: Abstract methods, constant properties, internal classes, enumeration classes

Classes implement interfaces: using the implements keyword

Features of the interface

Properties in interfaces default to public, static, final types: these members must be explicitly initialized; methods in interfaces default to public, abstract types.

There is no construction method in an interface at all, and it is possible to instantiate it by construction, but it allows you to define a reference variable of an interface type that references an instance of a class that implements the interface.

An interface cannot implement another interface, but it can inherit multiple interfaces.

Interfaces must implement their abstract methods by implementing classes. When a class implements an interface, it must implement all of its abstract methods, or define it as an abstract class without implementing its abstract methods.

Classes can inherit only one class, but they can implement multiple interfaces, separated by commas.

Interfaces and abstract classes

Common ground:
	Neither interface nor abstract class can be instantiated
	Interfaces and abstract classes are at the top of the inheritance tree
	Both interfaces and abstract classes can contain abstract methods
	Common classes that implement interfaces or inherit abstract classes must implement abstract methods within them
 Difference
	There may be non-abstract methods in abstract classes and only abstract or static or default-modified methods in interfaces
	A class can inherit only one direct parent, while an interface can achieve multiple inheritance
	Abstract classes can define static and common properties, while interfaces can only define static properties
	Abstract classes have their own constructs, interfaces have no
	Code blocks may exist in abstract classes, but not in interfaces

DEMO

/**
* Declare the interface and determine what can be in it
* 1,constant
* 2,Abstract method
* 3, default Modified non-abstract method (starting with JDK1.8)* 4, interface has no construction method
*/
public interface Usb {
	// Interface has no construction method
	// public Usb(){}
	/**
	* Only constants can be defined in an interface (no properties that are not constants)
	* 1,All properties in the interface are decorated with public static final by default
	* 2,Naming constants: All letters are capitalized, if there are more than one word, separated by an underscore
	* */
	int POWER_UNIT = 100 ;// Act as power supply unit
	/**
	* JDK1.8 Previously only abstract methods were allowed to be declared in interfaces
	* All methods are decorated with public abstrct
	*/
	void power();
	/**
	* JDK1.8 Start by allowing the definition of non-abstract methods decorated by default
	* This method is a public-decorated, non-static method (subclasses or subinterfaces can be overridden)
	*/
	default void show(){
		System.out.println("Each power supply unit is: "+POWER_UNIT) ;
	}
}

/**
* 1,Class implements the interface and implements the implementation with the keyword implements
* 2,If you don't want to be an abstract class, you need to implement all the abstract methods that "inherit" from the interface
*/
public class MiUsb extends Object implements Usb {
	/**
	* MiUsb What's in
	* All methods inherited from Object
	* Constants inherited from Usb
	* default method inherited from Usb (starting with JDK1.8)
	* Implement all abstract methods
	*/
	@Override
	public void power() {
		System.out.println("millet Usb Charger, power supply unit: "+POWER_UNIT);
	}
	@Override
	public void show() {
		Usb.super.show();
	}
}

public class Test {
	public static void main(String[] args) {
		// Declares a reference variable Usb u = null for an interface type;
		// Create an instance of the implementation class and assign its heap memory header address to the u variable
		u = new MiUsb();
		u.power();
	}
}

//A class implements multiple interfaces 

public interface Transfer {
	void transmission();
}

/**
* 1,Inheriting interfaces with interfaces
* 2,Interfaces can inherit constants, Abstract methods, default methods from parent interfaces
* 3,An interface can inherit multiple interfaces, separated by commas
*/
public interface UsbTypeC extends Usb , Transfer{}

/**
* A class implements multiple interfaces, separated by commas
*/
public class OppoUsb implements UsbTypeC,Usb{
	@Override
	public void transmission() {
		System.out.println("Oppo Mobile phone");
	}
	@Override
	public void power() {
		System.out.println("Oppo Mobile phone, power supply unit"+ POWER_UNIT);
	}
}

public class Test2 {
	public static void main(String[] args) {
		// Declare a reference variable of an interface type
		OppoUsb u = null;
		u = new OppoUsb();
		u.power();// Implement the method in Usb interface
		u.transmission();// Implements methods in the Transfer interface
	}
}

Internal Class

The internal classes are classified as follows:

Member internal class:
	Instance Internal Class
	Static Internal Class
 Local internal class:
	Anonymous Inner Class

DEMO

public class Human {/* Class body brackets */
	public static void main(String[] args){ // Method body start of main method
		int a = 250;
		System.out.println(a);
		class ON{ // Local Inner Class
		}
		ON oo = new ON();
		System.out.println(oo);
		class OFF{ // Local Inner Class
		}
	}// Method body of main method ends static String earth; //attribute: static attribute (class attribute)
	
	String name ; // Properties: Instance properties (instance variables)
	static class Country{ // static Inner Class
	}
	class Head{// Instance Internal Class (Member Internal Class) [Member Inner Class]
	}
	class Hand{// Instance Internal Class
	}
}

Get your own internal class

/**
* Gets all static and all member internal classes within a class
* Note: Local internal classes cannot be obtained
*/
public class GetInnerClass {
	public static void main(String[] args) {
		Class<?> c = Human.class;
		// Get internal classes inside c (static internal classes, member internal classes)
		Class<?>[] classes = c.getDeclaredClasses();// Gets a nonlocal inner class declared within this class
		for (int i = 0; i < classes.length; i++) {
			Class<?> cc = classes[i];
			System.out.println(cc);
		}
	}
}

You can also get which class you declare to be inside by an internal class

public class GetOutterClass {
	public static void main(String[] args) {
		Class<?> c = Human.Country.class;
		// Get an internal class declaration in that external class
		Class<?> oc = c.getDeclaringClass(); // Get the class that declares itself
		System.out.println(oc);
	}
}

Create instances of static internal classes

public class GetInstance1 {
	public static void main(String[] args) {
		/** Instances of static internal classes */
		Human.Country c = new Human.Country();
		System.out.println(c);
		/** Instances of Instance Internal Classes */
		Human h = new Human();// Create an instance of an external class
		Human.Hand hand = h.new Hand();// Create instances of internal classes based on instance h of external classes
		System.out.println(hand);
		// Or:
		Human.Head head= new Human().new Head();
		System.out.println(head);
	}
}

Anonymous Inner Class

If there is a local internal class that does not even have a name, it is an anonymous internal class, but it has a corresponding.Class file.

Create a new Class called TestAnonyous1.Then you create an interface called USB and provides a method (void transfer).Specific examples in TestAnonyous1: Using anonymity Name internal class implements interface.

DEMO

/**
* Create Anonymous Internal Class
*/
public class TestAnonymours1 {
	public static void main(String[] args) {
		// Compile-time type: The type declared by variable u is USB
		// Implementing interfaces with anonymous internal classes
		USB u = new USB(){
		@Override
		public void transfer() {
			System.out.println("USB Transferring");
		}
		};// When USB is treated as a corpse, the ghost {} gets up and instantiates it
		u.transfer();
		System.out.println(System.identityHashCode(u));
		// Get the runtime type of the instance created
		Class<?> c = u.getClass();// Any object can get its runtime type through getClass
		System.out.println(c);
		Class<?> oc = c.getDeclaringClass();// Try to get the external class that declares itself
		System.out.println(oc);// null indicates that an anonymous inner class is not declared directly inside the class body
		Class<?>[] inters = c.getInterfaces();
		for (int i = 0; i < inters.length; i++) {
			System.out.println(inters[i]);
		}
	}
}
public abstract class AbstractUSB implements USB{
// The abstract method transfer is inherited from the implemented interface
}
/**
* Create Anonymous Internal Class
*/
public class TestAnonymours2 {
	public static void main(String[] args) {
	// Create an instance of an abstract class (essentially an instance of its subclass type)
	// Inherit abstract classes with anonymous internal classes and implement their abstract methods
	AbstractUSB au = new AbstractUSB() {
		@Overridepublic void transfer() {
			System.out.println("AbstractUSB Transferring");
		}
	};
	au.transfer();
	Class<?> c = au.getClass();// Get Runtime Type of au Object
	System.out.println("Anonymous internal class: "+ c.getName());
	Class<?> sc = c.getSuperclass();
	System.out.println("The parent of an anonymous internal class: " + sc.getName() );
	}
}
/**
* Create Anonymous Internal Class
*/
public class TestAnonymours3 {
	public static void main(String[] args) {
	// Inherit a common class with an anonymous inner class
	// And override the method
	Object o = new Object(){
		@Override
		public String toString(){
		return "I am a ghost. ";
	}};
	System.out.println(o);
	System.out.println(o.getClass());
	System.out.println(o.getClass().getSuperclass());
	}
}

summary

1. Internal Classes
	Classes nested within another class
 2. Classification of internal classes
	Written directly within class body brackets:
	Static Internal Class, Non-Static Internal Class (Instance Internal Class, Member Internal Class)
	Not written directly within class body brackets, such as in methods, in code blocks: local internal classes
	If a local inner class does not even have a name, it is an anonymous inner class
 3. Questions:
	For Human.java, there is a corresponding Human.class file. Does the internal class have a corresponding.Class file?
	There are.class files. For static internal classes and instance internal classes, their corresponding.class names are:
		External Class Class Name$Internal Class Class Name.Class such as Country class in Human class corresponds to the byte code file name:Human$Country.class
	For local internal classes (named): their corresponding.Class file name is: external class class class name $Number internal class name.
		Number is where the internal class with that name appears in the external class (the number)
		
4. Can a class get its own internal class (static internal class, member internal class)
	GetInnerClass.java
	
5. Can an internal class get what class it declares to be inside: GetOutterClass.java

6. Create Instances of Internal Classes
	A>, Instances of local internal classes that can only be used inside the current code block,
	For example, the ON class of the main method inside the Human class, this class can only be used inside the main method
		class ON{//Local Inner Class
		}
		ON oo = new ON(); //Create an instance of a local internal class
		System.out.println(oo);
	B>, Create an instance of a static internal class:
		//External class.Static internal class variable name= new external class.Static internal class () Human.Country c = new Human.Country();
	C>, Create an instance of an instance internal class:
		Human h = new Human(); //Create an instance of an external class
		External class. Instance internal class variable name = External class instance. new instance internal class ();
		Human.Hand hand = h .new Hand();
7. Anonymous Internal Class
	If there is a local internal class that does not even have a name, it is an anonymous internal class, but it has a corresponding.Class file
	The name of the.Class file corresponding to the anonymous internal class is the external class class class name $number.class
	A>, Implement interfaces with anonymous internal classes: TestAnonymous1.java
	B>, inherit abstract classes with anonymous internal classes: TestAnonymous2.java
	C>, inherit common classes with anonymous internal classes: TestAnonymous3.java

Keywords: Programming Java Attribute Mobile

Added by phpScott on Thu, 08 Aug 2019 04:53:03 +0300