创建一个Dog类,属性public String color; public String size; public int age;
编写他的全构造方法。在Test类测试中去用全构造方法实例化的方式进行属性的初始化,并把这个属性打印出来(tostring)
Dog.java
package com.td;
public class Dog {
public String color;
public String size;
public int age;
public Dog(String size, String color, int age){ //全构造方法
this.color=color;
this.size=size;
this.age=age;
}
@Override
public String toString() {
return "Dog{" +
"color='" + color + '\'' +
", size='" + size + '\'' +
", age=" + age +
'}';
}
}
Test.java
package com.td;
public class test {
public static void main(String[] args) {
Dog dog = new Dog("大", "白", 19);
System.out.println(dog);
}
}
创建一个Cat类,属性private String color; privateString size; privateint age;
点出他所有属性的set和get 方法。在Test类测试中去用空构造方法去实例化对象之后,通过set的方法去给这个对象的所有属性赋值,并把这个属性打印出来(tostring)。
Cat.java
package com.td;
public class Cat {
private String color;
private String size;
private int age;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Cat{" +
"color='" + color + '\'' +
", size='" + size + '\'' +
", age=" + age +
'}';
}
}
Test2.java
package com.td;
public class test2 {
public static void main(String[] args) {
Cat cat=new Cat();//空构造方法
cat.setAge(3);
cat.setColor("白");
cat.setSize("小");
System.out.println(cat);
}
}
继承——使用关键字extends
Animal类
####Animal类
package com.td;
public class Animal {
private String color;
private String size;
private int age;
public Animal(String color, String size, int age) {
this.color = color;
this.size = size;
this.age = age;
}
public void eat(){
System.out.println("动物会吃");
}
public void sleep(){
System.out.println("动物会睡觉");
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Animal{" +
"color='" + color + '\'' +
", size='" + size + '\'' +
", age=" + age +
'}';
}
}
Dog类(继承了animal类)
package com.td;
public class Dog extends Animal{
public Dog(String color, String size, int age) { //无法自动继承父类的构造函数,需要自己定义
super(color, size, age);
}
// public void eat(){ 可以自己重写父类的方法
System.out.println("狗不仅会吃,还会吃骨头");
}
}
Test类
package com.td;
public class test {
public static void main(String[] args) {
Dog dog=new Dog("白","小",4);
dog.eat(); //方法是可以继承的
// Aniaml dog2=new Animal; 可以用父类去实例化对象
// dog2.eat();
System.out.println(dog);
dog.setSize("大");
System.out.println(dog.getSize());
}
}