1.构造方法:
构造函数、构造器、构建器-----------复用给成员变量初始化代码
- 作用:给成员变量赋初始值
- 与类同名,没有返回值类型(连void都没有)
- 在创建(new)对象时被自动调用
- 若自己不写构造方法,则编译器默认提供一个无参构造方法,
- 若自己写了构造方法,则不再默认提供
- 构造方法可以重载
2.this
- 指代当前对象,哪个对象调用方法它指的就是哪个对象
- 只能用在方法中,方法中访问成员变量之前默认有个this.
2.1this的用法
- this.成员变量名--------------访问成员变量
- 当成员变量和局部变量同名时,若想访问成员变量则this不能省略,其它一般省略
- this.方法名()------------------调用方法(一般不用,了解)
- this()----------------------------调用构造方法(一般不用,了解)
class Student {
//成员变量
String name;
int age;
String address;
//构造方法
Student(String name,int age,String address){
this.name = name; //zs.name="zhangsan"
this.age = age; //zs.age=25
this.address = address; //zs.address="LF"
}
//方法
void study(){
System.out.println(name+"在学习...");
}
void sayHi(){
System.out.println("大家好,我叫"+name+",今年"+age+"岁了,家住"+address);
}
}
//构造方法和this的演示
public class ConsDemo {
public static void main(String[] args) {
//Student zs = new Student(); //编译错误,Student类没有无参构造
Student zs = new Student("zhangsan",25,"LF");
Student ls = new Student("lisi",26,"JMS");
zs.sayHi();
ls.sayHi();
}
}
3.NULL
表示空,没有指向任何对象。若引用的值为null,则该引用不能再进行任何点操作了,若操作则发生NullPointerException空指针异常。
4.潜艇游戏第二天
图解(潜艇y坐标):
图解(坐标图):
4.1给6个类添加构造方法,并测试
4.1.1Battleship类
package cn.tedu.submarine;
import java.util.Objects;
/**
* 战舰
*/
public class Battleship {
/**
* 宽
*/
private int width;
/**
* 高
*/
private int height;
/**
* x轴
*/
private int x;
/**
* y轴
*/
private int y;
/**
* 命
*/
private int life;
/**
* 移动的速度
*/
private int speed;
public Battleship() {
this.width = 66;
this.height = 26;
this.x = 270;
this.y = 124;
this.life = 5;
this.speed = 20;
}
public Battleship(int width, int height, int x, int y, int life, int speed) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.life = life;
this.speed = speed;
}
/**
* 移动战舰的方法
*/
public void move(){
System.out.println("战舰移动");
}
/**
* 发射炸弹的方法
*/
public void shootBomb(){
}
@Override
public String toString() {
return "Battleship{" +
"width=" + width +
", height=" + height +
", x=" + x +
", y=" + y +
", life=" + life +
", speed=" + speed +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Battleship that = (Batt