Construction method
Create object
Features:
The name of the constructor is the same as the class name.
There is no return value, and void modification is not required.
Each class will have a parameterless constructor by default
You can also define a parameterized construction method. Once a parameterized construction method is defined, the default without parameters will be invalid
There can be multiple construction methods in a class, which are distinguished by method parameters.
/**
* 类中默认有一个元素的构造方法
*/
public People(){
System.out.println("调用构造方法");
}
/**
* 还可以在类中定义有参数的构造方法,一旦定义,默认元素的就会失效
*/
public People(String n){
name=n;
System.out.println("有参数的构造方法创建一个People对象");
}
public People(String n, int a){
name=n;
age=a;
}
People w = new People();//无参的
w.Play();
People z=new People("田");//一个参数
System.out.println(z.name);
People wing = new People("赵",21);//两个参数
System.out.println(wing.name+wing.age);
Method overload (overload)
The phenomenon of multiple methods with the same name in the same class-method overloading
When the method names are the same, how to distinguish methods:
1. Number of parameters
2. Types of parameters
3. Order of parameters
Objects and references
Pass by value
public class Reserve {
/*值传递*/
public static void main(String[] args) {
int a = 10;
Reserve r1 = new Reserve();
r1.test(a);//基本类型数据 是直接将值传递给其他的变量
System.out.println(a);
}
public void test(int t){
System.out.println(t);
t=5;
System.out.println(t);
}
}
operation result:
10
5
10
Call by reference
/*引用调用*/
public static void main(String[] args) {
Dog dog = new Dog();
dog.name="哈";
r2.test1(dog); //引用类型 传递的是对象的地址 并不是对象本身
System.out.println(dog.name);
}
public void test1(Dog dog1){
System.out.println(dog1.name);
dog1.name="嘿";
System.out.println(dog1.name);
}
哈
嘿
嘿