Java core technology -- interface, inheritance and polymorphism

1, Class inheritance

Inheritance is a very important concept in object-oriented development. It makes the whole program architecture flexible. Reusing some well-defined classes in the program can not only reduce the software development cycle, but also improve the maintainability and expansibility of the software.

The extensions keyword is used in Java to identify the inheritance relationship between the two classes.

package bao;

 
 class Demo1{
	public Demo1() {   //Construction method
		
	} 
	protected void domoni() {    //Member method
		
	}
	protected Demo1 doot() {  //The return value type of the method is Demo1
		return new Demo1();  
		
	}
 
}
 
 class Demo2 extends Demo1{   //Inherit parent class 
	 public Demo2() {        //Construction method
		 super();            //super calls the parent class constructor
		 super.domoni();    //super calls the parent class member method
	 }
	 
	 public void domoi11() {    //New method
		 
	 }
	 public void domoni() {     //Override parent method
		 
	 }
	 
	 protected Demo2 doot() {       //Override the parent class method. The return value type of the method is Demo2
		return new Demo2();
	 }
 }

Inheritance code analysis:

package bao;

 
 class Demo1{
	public Demo1() {   //Construction method
		System.out.println("I'm a parent Demo1");
		
	} 
	
 
}
 
 class Demo2 extends Demo1{   //Inherit parent class Demo1 
	 public Demo2() {        //Construction method
		 System.out.println("I'm a subclass Demo2");
	 }
	
 }
 
  class Demo3 extends Demo2{   
	 Demo3(){
		 System.out.println("I'm a subclass Demo3");
		 
	 }
	 public static void main(String[] args) {
		Demo3 d=new Demo3();     //Instantiate subclass objects
	}
 }


/*Output results:
I am the parent Demo1
 I am subclass Demo2
 I am subclass Demo3
 */

2, Object class

Object class is a special class. It is the parent class of all classes and the highest class in the Java class layer. In essence, any class in Java is its subclass.

1. getClass() method

(1) The getClass () method is the class that gets the object calling the method; getClass().getName() can get the path of this class.

getClass().getname();

(2) After the object Class is obtained through the getClass() method, the relevant attributes and methods in the Class can be obtained through the Class.

2. toString() method

The function of the toString() method changes an object to a string.

package bao;

 
 public class Demo1{
	 
		public String toString() {      //Rewrite toString() method
			return "stay"+getClass().getName()+"Override in class toString()method";
			
			
		}
	 public static void main(String[] args) {
		
		System.out.println(new Demo1());
	}


 }


/*Output results:
Override the toString() method in the bao.Demo1 class
 */

3. equals() method

In the Java language, there are two ways to compare objects: the "= =" operator and the equals() method.

package bao;
 
import java.util.Arrays;
 
public class Demo1 {
    public static void main(String[] args) {
        String str=new String("aaa");
        String str1=new String("aaa");
        String str2=str;
        //Use the "= =" operator to compare str1 and str2
        System.out.println(""=="operator comparison  str1 And str2 Results:"+(str1==str2));
        //Compare str1 and str2 using the "equals()" method
        System.out.println(""equals()"Method comparison str1 And str2 Results:"+str1.equals(str2));
       }
}
 
/*Output results:
"=="Operator to compare str1 with str2: false
"equals()"Method to compare the results of str1 and str2: true
*/

"= =": compares whether the addresses of two objects are the same

equals(): compares whether the contents of two objects are the same

3, Conversion of object types

1. Upward transformation

For example, if a duck is a kind of poultry and poultry is a kind of animals, the duck object can also be regarded as an animal object.

fulei  dx=new zilei();

fulei: parent class

zilei: subclass

Demo1 represents poultry and demo2 represents ducks. Use Demo2 duck class to inherit Demo1 poultry, then call the main method draw() to call the parent class method.

package bao;

 
 public class Demo1{                  //Poultry 
	 
	 public static void draw(Demo1 jia) {     //Methods of poultry

	}
public static class Demo2 extends Demo1{
	public static void main(String args[]) {
		Demo2 ya=new Demo2();       //Instantiate the object reference of the duck class
		draw(ya);
	}
}

 }

2. Downward transformation

Through the upward transformation, it can be inferred that the downward transformation is to convert more abstract classes into more specific classes. Such a transformation usually has problems. For example, we can't say that quadrilateral is a kind of parallelogram, and we can't say that all birds are pigeons, which is very illogical. It can be said that the subclass object is always an instance of the parent class, but the parent class object is not necessarily an instance of the subclass.

fulei a=new zilei();

zilei b=(zilei)a;

fulei: parent class

zilei: subclass

package bao;

 
 public class Demo1{                  //Poultry 
	 
	 public static void draw(Demo1 jia) {     //Methods of poultry

	}
public static class Demo2 extends Demo1{
	public static void main(String args[]) {
		
		draw(new Demo1());    //Think of ducks as poultry
		Demo1 jia=new Demo2();   
		
		//Demo2 ya=jia;    It is wrong to assign a poultry object to a duck object
	
		Demo2 ya=(Demo2)jia;	//It is correct to assign a poultry object to a duck object and cast it into a subtype
	}
}

 }

4, instanceof judge object type

When performing a downward transformation in a program, if the parent object is not an instance of a child object, a ClassCastException exception will occur. Therefore, before performing a downward transformation, you need to develop a good habit of judging whether the parent object is an instance of a child object. This judgment is usually done using the instanceof operator.

zilei instanceof fulei

zilei: subclass objects

fulei: parent object

package bao;

 
 public class Demo1{      
	 public static void draw(Demo1 q) {
		 
	 }
	}
 class Demo2 extends Demo1{
	 
 }
 class Demo3{
	 
 }
class Demo4 extends Demo1{
	 public static void main(String args[]) {		 
			Demo1 a=new Demo1();     //Parent class instantiation
			if(a instanceof Demo4) {   //Judge whether the parent object is an instantiation of Demo4 subclass
				Demo4 d=(Demo4)a;
			}
			  
			if(a instanceof Demo2) {   //Judge whether the parent object is an instantiation of Demo2 subclass
				Demo2 s=(Demo2)a;
			}
		 
		}
	 
 }
 

5, Method overloading

Method overloading means that more than one method with the same name is allowed in the same class, as long as the number or type of parameters of these methods are different.

package bao;

 
 public class Demo1{ 
	 
	 public static int add(int a,int b) {  //Define a method
		 return a+b;
	 }
	 public static double add(double a,double b) {  //Different parameter types constitute overloads.
		 return a+b;
	 }
	 public static int add(int a) {  //The number of parameters is different, which constitutes an overload.
		 return a;
	 }
	 /*
	  *  public static int add(double b,int a)
	  *  public static int add(int a,double b)
	  *  The parameters in the above two lines are in different order, which constitutes an overload
	  *  
	  * */
	 public static int add(int a,double b) {  //The order of parameters is different, which constitutes an overload.
		 return 1;
	 }
	 
	 public static void main(String args[]) {
		System.out.println("call add(int a,int b)method:"+add(1,2));
		System.out.println("call add(double a,double b)"+add(2.1,3.6));
		System.out.println("call add(int a)"+add(1));
	}
 }
 
 

 


/*Output results:
Call add(int a,int b) method: 3
 Call add(double a,double b)5.7
 Call add(int a)1

 */

1. Different parameter types constitute overloads.

2. The order of parameters is different, which constitutes an overload.

3. The number of parameters is different, which constitutes an overload.

6, Polymorphism

Polymorphism means that the same interface performs different operations using different instances, as shown in the figure:

Polymorphism is an important part of object-oriented programming. In Java, method Overloading and Overriding are usually used to realize class polymorphism.

package bao;

 
 public class Demo1{ 
	 
	private Demo1[] qt=new Demo1[6];
	private int index=0;
	public void draw(Demo1 a) {
		if(index<qt.length) {
		qt[index]=a;
		System.out.println(index);
		index++;
		}
		
	}
	
	 
	 public static void main(String args[]) {
		
		 Demo1 a=new Demo1();
		 a.draw(new Demo2());  //Call black and white printing
		 a.draw(new Demo3());   //Call color printing
	}
 }

//Defines the class Demo2 for black-and-white printing
	 
	 class Demo2 extends Demo1{
		 public Demo2() {
			 System.out.println("Black and white printing");
		 }
	 }
 //Defines the class Demo3 for color printing
	 class Demo3 extends Demo1{
			 public Demo3() {
				 System.out.println("Color printing");
				 
			 }
		 }



/*Output results:
Black and white printing
0
 Color printing
1

 */

7, Abstract classes and interfaces

1. Abstract class

When solving practical problems, the parent class is generally defined as an abstract class, which needs to be used for inheritance and polymorphism. For example, pigeons inherit birds, birds inherit animals, etc.

The keyword of the abstract class is abstract.

public abstract Yesst{

abstract void testAbstract();  //Define abstract methods

}

2. Interface

(1) Interface

Interface is an extension of abstract class, which can be regarded as a pure abstract class. All methods in the interface have no method body.

The definition interface keyword is interface.

The implementation interface keyword is implements.

package bao;

 

interface jiekou{         //Define interface
	 public void draw();  //Definition method	
		 }
//Defines a parallelogram, which inherits the quadrilateral class and implements the jiekou interface
	class Demo2 extends Demo1 implements jiekou{  
			public void draw() {    //Since this class implements the interface, the draw() method is required  
				System.out.println("parallelogram.draw()");
			}
			void doany() {   //Override parent class
				
			}
		}
	
	class Demo3 extends Demo1 implements jiekou{  
		public void draw() {    
			System.out.println("square.draw()");
		}
		void doany() {
			
		}
	}
	
	  class Demo4 extends Demo1{    //Define quadrilateral class
		void doany() {   
			
		}

	}
	  
	  public class Demo1{    //Define quadrilateral class
			public void doAny() {
			}
			
			
	 public static void main(String[] args) {
		jiekou[]d= {               //Interfaces can also be transformed upward
				new Demo2(),new Demo3()};
		for(int i=0;i<d.length;i++) {
			d[i].draw();  //Call the draw() method
		}
	}
	 
}



/*Output results:
Parallelogram (. Draw)
Square (. Draw)

 */

(2) Interface and inheritance

Class class name implements interface 1, interface 2,..., interface n

interface intf1{

}

interface intf2 extends intf1{

}

8, Attach

Differences between public static void main(String[] args) and public static void main(String args []):

String args []: in terms of type alone, it belongs to string type, but in terms of variable itself, it is an array type. Therefore, when combined, it indicates that this variable is an array of string type, that is, all elements in the array are of string type.

String[] args: in terms of type, it belongs to string array type, but in terms of variable itself, it is a simple reference variable. Therefore, this method can more clearly reflect whether it is an array. Because from the type, it can be directly seen that the variable is an array type reference.
 

Keywords: Java Back-end JavaSE

Added by Boerboel649 on Tue, 26 Oct 2021 15:12:47 +0300