Java -- reference type Usage Summary

reference type

In actual development, the use of reference type is very important and common. We can further master the usage of reference types on the basis of understanding the usage of basic types. A basic type can be a member variable, a parameter of a method, or a return value of a method, so can a reference type.

  • class as member variable
    When defining a Role class, the code is as follows:
class Role {    
int id; // Role id       
int blood; // Life value       
String name; // Role name}

Use int type for Role id and life value, and String type for name. At this point, String itself is a reference type. Because it is similar to a constant, it is often ignored that it is a reference type. If we continue to enrich the definition of this class, add weapons, wear equipment and other attributes to Role, how will we write it?
Defining weapon classes will increase attack power:

class Weapon {   
	String name; // Weapon name         
	int hurt; // Damage value}

The definition of wearing helmets will increase the defense ability, that is to say, increase the health value:

class Armour {    
String name;// Name of equipment        
int protect;// Defense value 

Define role class:

class Role {     
	int id;     
	int blood;     
	String name;     
	// Add weapon attribute     
	Weapon wp;     
	// Add armor attribute     
	Armour ar;       
	// Provide get/set method     
	public Weapon getWp() {       
	  return wp;     }     
	  public void setWeapon(Weapon wp) {         
	  this.wp = wp;     }     
	  public Armour getArmour() {         
	  return ar;     }     
	  public void setArmour(Armour ar) {    = ar;     }       
	  // Attack method     
	  public void attack(){         
	  System.out.println("Use"+ wp.getName() +", cause"+wp.getHurt()+"Point injury");       }       
	  // Wearing armor     
	  public void wear(){         
	  // To increase defense is to increase the value of blood         
	  this.blood += ar.getProtect();         
	  System.out.println("Wear"+ar.getName()+", Health increased"+ar.getProtect());     
	  }   }

Test class:

public class Test {    
	public static void main(String[] args) {         
	// Create a wepon object              
	Weapon wp = new Weapon("Dragon carving knife" , 999999);                 
	// Creating an Armour object           
	Armour ar = new Armour("Kirin nail",10000);           
	// Create a Role object           
	Role r = new Role();                          
	// Set weapon properties           
       // Set armor properties      
       // attack          
        // Wearing armor       
         r.wear();       }    } 
         //Output result: 
         //Use dragon slaying knife,cause999999Point injury 
         //Wear Unicorn armor ,Health increased10000
  • interface as member variable
    Interface is the encapsulation of methods. In the corresponding game, it can be regarded as the skill of expanding game characters. So, if we want to expand more powerful skills, we can add interface as member variable in Role to set different skills.
    Define interface:
// Magic Attack 
public interface FaShuSkill {     
	public abstract void faShuAttack(); }

Define role class:

public class Role {     
	FaShuSkill fs;       
	public void setFaShuSkill(FaShuSkill fs) {         
	this.fs = fs;     }     
	// Magic Attack      
	public void faShuSkillAttack(){         
	System.out.print("Launch a spell attack:");         
	System.out.println("Attack completed");     } }

Define the test class:

public class Test {     
	public static void main(String[] args) {         
	// Create a game character         
	Role role = new Role();         
	// Set character spell skills         
	role.setFaShuSkill(new FaShuSkill() {
     public void faShuAttack() {                 
     System.out.println("Overrun the whole world and go anywhere as one pleases");             }         });           
     // Launch a spell attack         
     // Skill replacement         
     role.setFaShuSkill(new FaShuSkill() {             
     public void faShuAttack() {                 
     System.out.println("Reversing the universe");             }         });        
      // Launch a spell attack         
      role.faShuSkillAttack(); }      
      //Output result: 
      //Launch a spell attack:The attack is over   
      //Launch a spell attack:Reverse heaven and earth attack completed

We use an interface as a member variable to change skills at any time. This design is more flexible and enhances the scalability of the program.
When an interface is a member variable, its assignment is actually a subclass object assigned to it.

  • interface as method parameter and return value type
    When an interface is a parameter to a method, what does it need to pass? When an interface is the return value type of a method, what does it need to return? Yes, they are all subclass objects. ArrayList class is not new to us. Looking at the API, we find that, in fact, it is the implementation class of java.util.List interface. Therefore, when we see the List interface as a parameter or return value type, we can certainly pass or return the ArrayList object.
    Observe the following method: get all the even numbers in a collection.
    Define method:
public static List<Integer>getEvenNum(List<Integer> list) {     
// Create a collection that holds even numbers     
ArrayList<Integer> evenList = new ArrayList<>();    
 // Traverse the collection list, judge whether the element is even, and add it to the eventlist     
 for (int i = 0; i < list.size(); i++) {         
 Integer integer = list.get(i);        
  if (integer % 2 == 0) {             
  evenList.add(integer);         }     }     
  /*      Return even set
   Because the return value type of getEvenNum method is List, and ArrayList is a subclass of List, evenList can return       */        
   return evenList; }

Call method:

public class Test {     
	public static void main(String[] args) {         
	// Create the ArrayList collection and add numbers         
	ArrayList<Integer> srcList = new 
	 for (int i = 0; i < 10; i++) {             
	 srcList.add(i);         }          
	  /*         Get even collection because the parameter of getEvenNum method is List, and ArrayList is a subclass of List, so srcList can pass           */            
	  List list = getEvenNum(srcList);         
	  System.out.println(list);     } }

When an interface is a parameter, its subclass object is passed.
Interface returns its subclass object when it is the return value type

Published 47 original articles, won praise 0, visited 325
Private letter follow

Tags: Attribute Java

Posted on Fri, 14 Feb 2020 01:26:52 -0500 by phpQ2