1.this关键字
①一般写在实体类中,表示的是当前的对象;
②可以使用this调用属性和方法;
③this关键字可以调用构造方法(很少用);
注意:(1)一定是在构造方法中调用另一个构造方法
(2)在构造方法中调用其他构造方法的时候一定要写在首行
class Person {
String name;
int age;
public Person () {
System.out.println("Line 9: "+ this);//代表是当前的对象
this.name = "狗蛋";//this可以调用属性
}
public void eat () {
//this可以调用方法
this.test();
}
public void test () {
System.out.println("嘻嘻");
}
}
public class Demo1 {
public static void main(String[] args) {
Person person1 = new Person();
System.out.println(person1);//对象的内存地址 15db9742
System.out.println(person1.name);
person1.eat();
Person person2 = new Person();
System.out.println(person2);//对象的内存地址6d06d69c
System.out.println(person2.name);
}
}
2.方法的参数可以是一个类对象
方法的参数可以是八大基本数据类型、String、数组和类对象
例:人可以生孩子,孩子可以玩玩具,玩具被玩(在玩具类中打印玩具被玩)
class Adult {//成年人类
public void birth (Child child) {
Toy toy2 = new Toy();
child.playToy(toy2);
}
}
class Child {
public void playToy (Toy toy) {
toy.bePlay();
}
}
class Toy {
public void bePlay () {//玩具被玩
System.out.println("被玩,很开心");
}
}
public class Demo6 {
public static void main(String[] args) {
Adult adult = new Adult();
Child child= new Child();
adult.birth(child);
}
}
3.多类合作
一个类对象可以作为另外一个类的属性
class RenLei {//人类
String name;
int age;
BigDog bigDog;//bigDog这个对象带了三个数据 牛彩云 3 黑色
}
class BigDog {
String name;
int age;
String color;
}
public class Demo8 {
public static void main(String[] args) {
BigDog