JAVA notes -- object oriented (Part 2)

catalogue

1, One to one relationship of objects

2, static keyword modifies properties and methods

1. Use the static keyword to decorate an attribute

2. Use the static keyword to decorate a method

3, Memory structure diagram and main method and code block

1. Structure diagram of loading class file into memory

2. main method

3. Code block

4, Single case design mode

1. Two implementation methods

2. Math instead of singleton

5, Object array case

1. Object array and management

1, One to one relationship of objects

One to one relationship between two objects:

For example: a Hero versus a Weapon

To express the one-to-one relationship of an object is actually to define the object type as an attribute

Two way one-to-one: you can get the information of the other party through either party

One way one to one

public class OneToOne {
 
	public static void main(String[] args) {
		Husband h=new Husband("a cowboy",'male');
		Wife w=new Wife("woman weaver",22);
		//Association relationship
		h.setWife(w);
		w.setHusband(h);
		
		System.out.println(h.getName()+"My wife is"+h.getWife().getName()+",She this year"+h.getWife().getAge()+"Years old.");
        //Output: Niu Lang's wife is Zhinv. She is 22 years old.
	}
 
}
/**
 * 
 * Husband class
 *
 */
public class Husband {
	private String name;
	private char sex;
	private Wife wife;//Associate wife classes and represent each other's classes as their own attributes
	
	public Husband(String name, char sex) {
		this.name = name;
		this.sex = sex;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the sex
	 */
	public char getSex() {
		return sex;
	}
	/**
	 * @param sex the sex to set
	 */
	public void setSex(char sex) {
		this.sex = sex;
	}
 
	public Wife getWife() {
		return wife;
	}
 
	public void setWife(Wife wife) {
		this.wife = wife;
	}
 
}

/**
 * 
 * Wife class
 *
 */
public class Wife {
	private String name;
	int age;
	private Husband husband;//Associate husband classes and represent each other's classes as their own attributes
	
	public Wife(String name, int age) {
		this.name = name;
		this.age = age;
	}
 
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
 
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
 
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
 
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	
	public Husband getHusband() {
		return husband;
	}
 
	public void setHusband(Husband husband) {
		this.husband = husband;
	}
	
 
}

2, static keyword modifies properties and methods

1. Use the static keyword to decorate an attribute

Variables declared as static are essentially global variables

public class Test{
    public static void main(String[] args){
        Role beibei = new Role("Liu Bei","Shu Kingdom");
        Role yunchang = new Role("Cloud length","Shu Kingdom");
        Role feifei = new Role("Fei Zhang","Shu Kingdom");
        System.out.println(beibe.getInfo());
        System.out.println(yunchang.getInfo());
        System.out.println(feifei.getInfo());
    }
}

//role
class Role{
    private String name;
    private String country;
    public Role(String name,String country){
        this.name = name;
        this.country = country;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public void setCountry(String country){
        this.country = country;    
    }
    public String getCountry(){
        return country;
    }
    public String getInfo(){
        return "name="+name+",country="+country;
    }
}

 

At this time, if you look at the memory, you will find that there is a waste of memory, because it is all Shu, which has been stored three times; So it is optimized

public class Test{
    public static void main(String[] args){
        Role beibei = new Role("Liu Bei");
        Role yunchang = new Role("Cloud length");
        Role feifei = new Role("Fei Zhang");
        System.out.println(beibe.getInfo());
        System.out.println(yunchang.getInfo());
        System.out.println(feifei.getInfo());
    }
}

//role
class Role{
    private String name;
    //Optimized definition
    private static String country="Shu Kingdom"; //Static variable (global variable)
    public Role(String name,String country){
        this.name = name;
        this.country = country;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public String getInfo(){
        return "name="+name+",country="+country;
    }
}

 

Static variables or methods do not belong to objects and depend on classes;

Static variables are global variables, and the life cycle is from the class is loaded to the end of the program;

Only one static variable is saved and stored in the static method area;

Static variables are shared by all objects of this class;

It is recommended not to use the object name to call static data, but directly use the class name to call;

static modifies a method, then the method belongs to a class, not an object, and is called directly with the class name;

2. Use the static keyword to decorate a method

Usually, a method is defined as static in a class, that is, this method can be called without the object of this class;

Static methods cannot access non static data;

It can only call other static methods;

It cannot reference this or super in any way;

public class Test{
    public static void main(String[] args){
        Role beibei = new Role("Liu Bei");
        Role yunchang = new Role("Cloud length");
        Role feifei = new Role("Fei Zhang");
        System.out.println(beibe.getInfo());
        System.out.println(yunchang.getInfo());
        System.out.println(feifei.getInfo());
    }
}

//role
class Role{
    private String name;
    //Optimized definition
    private static String country="Shu Kingdom"; //Static variable (global variable)
    public Role(String name,String country){
        this.name = name;
        this.country = country;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    //Non static methods cannot access non static data
    public static void setCountry(String country){
        Role.country = country;
    }
    public String getInfo(){
        return "name="+name+",country="+country;
    }
}

Use the static keyword to decorate a class to (described later)

3, Memory structure diagram and main method and code block

1. Structure diagram of loading class file into memory

2. main method

Main method:

public static void main (String[] args){

/ / code block

}

Public: public, with maximum access rights;

Static: static, without creating objects;

void: indicates that there is no return value and there is no need to return the result to the JVM;

main: method name, fixed method name

String[] args: indicates that the parameter is a string array, which can be passed in when calling the method

3. Code block

Common code block: a code block written directly in a method;

Construction block: a code block defined in a class; It is called when creating an object, which is better than the execution of the construction method;

public class Test{

        public static void main(String[] args){
            Student s = new Student(); 
            Student s1 = new Student();
        }
}

class Student{

    {
       System.out.println("I'm building blocks"); 
    }
    public Student(){
        System.out.println("I am the construction method"); 
    }

    public void study(){
        //Limit scope
        {
            int i = 10;
            System.out.println("I'm a normal code block"); 
        }
    }
}

Static code block: the code block declared with static in the class is called static code block,

Static code block, executed only once, executed first.

When called for the first time, it will only be executed once, which is better than building blocks;

In project development, static code blocks are usually used to initialize data that is called only once. For example: run the program to read the configuration data;

public class Test{

        public static void main(String[] args){
            Student s = new Student(); 
            Student s1 = new Student();
        }
}

class Student{
     static{
        System.out.println("Static code block"); 
    }

    {
       System.out.println("Tectonic block"); 
    }
   
    public Student(){
        System.out.println("Construction method"); 
    }

    public void study(){
        //Limit scope
        {
            int i = 10;
            System.out.println("I'm a normal code block"); 
        }
    }
}

4, Single case design mode

Singleton design pattern: ensure that a class has only one instance and provide a global access point to access it.

1. Privatization of construction methods

2. Declare an object of this class

3. Provide a static method to get the object instance

1. Two implementation methods

Lazy: when the getInstance method is called for the first time, the object is created and released after the program ends

Hungry Chinese style: after the class is loaded, the object is created and released at the end of the program

public class Test{

        public static void main(String[] args){
            //Singleton1 s = new Singleton1();
            Singleton1 s = Singleton1.getInstance();
            s.print()
            Singleton1 s1 = Singleton1.getInstance();
            s1.print()

            Singleton2 s = Singleton2.getInstance();
            s.print()
            Singleton2 s2 = Singleton2.getInstance();
            s2.print()
        }
}


//Lazy style
class Singleton2{
    private Singlenton2(){}
    private static Singleton2 s; 
    public static Singleton2 getInstance(){
        if(s==null){
            s = new Singleton2();
        }
        return s;
    }
    public void print(){
        System.out.println("Test method 2"); 
    }
    
}

//Hungry Han style
class Singleton1{
    private Singlenton1(){}
    private static Singleton1 s = new Singleton1();
    public static Singleton1 getInstance(){
        return s;
    }
    public void print(){
        System.out.println("test method"); 
    }
    
}

Lazy type: occupy memory time period, low efficiency (lazy loading, delayed loading); There may be security problems in multithreading;

Hungry Han style: long memory occupation time and high efficiency;

Why should we use singleton in the project? What are the benefits of singleton?

When designing some tool classes (usually tool classes have only function methods and no attributes)

Tool classes may be called frequently

The purpose is to save the memory consumption caused by repeatedly creating objects

2. Math instead of singleton

Can we use construction method privatization + static method to replace singleton?

  class Tools{

        private Tools(){};

        public static void print1(){ }

        public static void print2(){ }

}      

5, Object array case

1. Object array and management

When assigning a value to an array object, each object is assigned a value directly to the array object.

public class Test{
    public static void main(String[] args){
        ChickenManager cm = new ChickenManager(5);
        cm.add(new Chicken(1,"Small",10));
        cm.add(new Chicken(2,"waiter",8));
        cm.add(new Chicken(3,"the other woman",6);
        cm.add(new Chicken(4,"Xiao Si",4));
        cm.add(new Chicken(5,"Small five",2));
        cm.add(new Chicken(6,"Xiao Liu",1));
        System.out.println("Length of array:"+cm.length());
        cm.printAll()

        Chicken c = cm.find(5);
        c.print();

        cm.update(new Chicken(1,"Junior one",9));
        cm.printAll();


    }
}

//Management class
class ChickenManager{
    
    private Chicken[] cs = null;
    private int count = 0; //Record the number of elements of the current array (subscript)
    public ChickenManager(int size){
        if(size>0){
            cs = new Chicken[size];
        }else{
            cs = new Chicken[5];
        }
    }
    public int length(){
        return cs.length
    }
    //Add: implement dynamic array
    public void add(Chicken c){
        if(count>=cs.length){ //Indicates that the array is full and needs to be expanded
            //Algorithm 1: expand half the size of the original array CS length*3/2+1

            //Algorithm 2: double the original array CS length*2
            int newLen = cs.length*2 ;       
            cs=Arrays.copyOf(cs,newLen);
        }
        cs[count]=c;
        count++;
    }
    //delete
    public void delete(int id){
        for(int i=0;i<count;i++){
            if(cs[i].getId()==id){
                //The object to be deleted is found. Move the object after the object forward one bit
                for(int j=i;j<count-1;j++){
                    cs[j] = cs[j+1];
                }
                //Assign the last object null
                cs[count-1]=null;
                count--;
                break;
            }
        }   
    }
    //to update
    public void update(Chicken c){
        Chicken temp = find(c.getId());
        if(temp!=null){
            temp.setName(c.getName());
            temp.setAge(c.getAge());
        }
    }
    //lookup
    public Chicken find(int id){
        for(int i=0;i<count;i++){
            if(cs.[i].getId==id){
                return cs[i];
            }
        }
        return null;
    }
    //Output all
    public void printAll(){
        for(int i=0;i<count;i++){
            cs[i].print();
        }
    }
}


//Chicken class (data object) value object (VO) can also be called entity
class Chicken{
    
    private int id;
    private String name;
    private int age;
    public Chicken(){}//In general, it is best to keep the default construction method
    public Chicken(int id,String name,int age){
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public void setId(int id){
        this.id = id;
    }
    public int getId(){
        return id;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){
        return age;
    }
}

Dynamic array:

Array is a linear data structure;

Array is not suitable for deletion, insertion and other operations. It is suitable for addition, search and traversal;

Keywords: Java Back-end

Added by anujgarg on Fri, 11 Feb 2022 06:50:15 +0200