Head first java Chapter 9

Head First Java Chapter 9 The Past and Present of Objects

welcome

Hello there! This is my reading notes during the winter vacation where the New Crown Virus rages. I intend to record the knowledge I learned during the reading process from the ninth chapter.

Two areas

  1. Heap : The living space of an object.
  2. Stack : The method calls and the living space of variables.

Two variables

Instance variables: declared in the class, outside the method, representing the "field"
local variables of independent objects : declared in the method, or the parameters of the method They are temporary and only exist during method invocation.

Local variables

All local variables exist in the corresponding stack blocks on the stack.

Object reference variables and primitive Variables of the main data type are placed on the stack.

Whether it is an instance variable or a local variable, the object itself will be on the heap.

Instance variable

1. An object with an instance variable of primitive primary data type, the space required by the variable is in the object.
2. The object has variables of other objects. Assuming it is a Dog object, Java will only leave the reference of Dog instead of the space used by the object itself. When the reference variable is assigned, it will occupy space on the heap.

Constructor

The object is executed before it is assigned and referenced.

public class Duck{
	public Duck()
	{
		System.out.println("Quack");
	}
}

public class UseDuck{
	public static void main(String[] args)
	{
		Duck d = new Duck();//启动构造函数
	}
}	

If you want an object to be initialized before being used, the best way is to put the initialization code in the constructor.

public class Duck{
	int size;
	public Duck(int ducksize){
		System.out.println("Quack");
		size = ducksize;
		System.out.println("size is "+size);
	}
}
public class UseADuck{
	public static void main(String[] args){
		Duck d = new Duck(42);//传值给构造函数
	}
}

As long as you have your own constructor, you will tell the compiler again. My own constructor doesn't matter.

You can use the parameterless constructor to call the default value we provide to construct the function. But if the default value cannot be provided, the parameterless constructor with the default value is unreasonable.

Published 27 original articles · praised 2 · visits 680

Guess you like

Origin blog.csdn.net/qq_44273739/article/details/104187231