构造方法:
①、方法名和类名相同
②、没有返回值类型,就是在方法的返回值类型处空下来
③、在创建一个类的新对象时,系统会自动的调用该类的构造方法完成对新对象的初始化
4 主要作用是完成对新对象属性的初始化,严重鄙视在构造方法中执行一些方法操作,如连接数据库等
5 在一个类中可以有多个构造方法,即构造方法可以被重载
6 每个类都有一个默认的构造方法
分为 隐式无参(没有的时候的默认) 显式无参(有构造方法不传递参数) 显式有参(有构造方法并且传递参数)
package test2;
public class Method_construct {
public static void main(String[] args) {
Person per = new Person(30,"xiaoming");
per.call();
}
}
class Person{
int age;
String salary;
public Person(int a,String b) {
this.age = a;
this.salary = b;
}
void call(){
System.out.printf("age is %d and salary is %s",age,salary);
}
}
***tips: in same pakage, we can not create two class in same name even in different java file.***
this:
this代词使用时注意,this不能在该类定义的外部使用,只能在该类定义的方法中使用。
this关键字主要有三个应用:
(1)this调用本类中的属性,也就是类中的成员变量;
(2)this调用本类中的其他方法;
(3)this调用本类中的其他构造方法,调用时要放在构造方法的首行。
public class Student { //定义一个类,类的名字为student。
public Student() { //定义一个方法,名字与类相同故为构造方法
this(“Hello!”);
}
public Student(String name) { //定义一个带形式参数的构造方法
}
}
调用Student的构造方法Student
public class testThis {
public static void main(String[] args) {
testThis t= new testThis();
t.A().B();
}
testThis A() {
System.out.println("A");
return this;
}
void B() {
System.out.println("B");
}
}
t.A().B()
这里的this表示当调用方法A时,会执行完A然后返回到类t,然后可以直接接着调用B方法
关于新建对象的堆栈:
静态变量:不会随着类的初始化而变化,可以直接通过类名.变量调用。
该变量被分配在内存中的静态区。
静态方法:类方法中只可以访问静态变量不可以访问成员变量。但成员方法中既可以访问类变量也可以访问成员变量