构造方法
构造方法的格式,[修饰符] 类名(形参列表){//n条语句}
具体与方法类似,属于一种特殊的方法
构造方法的名字要与类名相同
不用再写返回值,但是其有返回值
用关键字new调用。
下面是引用的代码
public class Point {
double x,y;
public Point(double _x,double _y){
x=_x;
y=_y;
}
public static double distance(Point p){
double result=p.x+p.y;
return result;
}
public static void main(String[] args) {
Point P= new Point(4.5,4.5);
System.out.println(distance(P));
}
}
下面是构造方法的重载,与方法的重载类似
代码如下:
public class People {
int age;
int high;
String name;
int room;
public People(){
}
public People(int age,int high){
this.age=age;
this.high=high;//this表示已经创建好的对象
}
public People(int age,String name,int room){
this.age=age;
this.name=name;
this.room=room;
}
public static void say(People p){
System.out.println("我的名字是"+p.name+"多大"+p.age+"在哪住"+p.room);
}
public static void main(String[] args) {
People P=new People(18,"lan",503);
People P2=new People(18,56);
say(P1);
}
以上就是方法的重载。
this关键字的用法
在普通方法中this指的是当前的对象
在构造方法中this指的是要初始化对象
同时this不能在static方法中引用
因为this指的是对象,而static指的是类,并不是对象。
而且在static方法中,只能引用static方法,不能引用非静态的方法
但是在非静态方法中可以引用静态的方法。