一、今天学习的新内容:
今天练习5.8的的习题。
二、遇到的问题:
无。
三、明天计划:
明天开始学习6.1和6.2的内容。
具体内容如下:
1.请分别定义父类people和子类Student,观察子类是如何共享父类属性和方法的。
public class People1 {
public int age;
public String name;
public String sex;
public People1() {
System.out.println("父类无参构造方法!");
}
public void say() {
System.out.println("父类方法say()");
}
public String getName() {
return this.name;
}
public static void main(String[] args) {
People1 s=new student(12,"小明","man",100021);
s.say();
String str=s.getName();
System.out.println("父类属性name:"+str);
}
}
class student extends People1{
private int idNumber;
public student() {
}
public student(int a,String n,String s,int id) {
age=a;
name=n;
sex=s;
idNumber=id;
System.out.println("子类含参构造方法!");
}
public student(int i) {
idNumber=i;
System.out.println("子类含参构造方法!");
}
}
测试截图:
2.在题1People中定义final方法,然后在类student 类中定义与该final相同的方法,观察student的变化
在父类中的final方法不能在子类student中重写。
public class People1 { public int age; public String name; public String sex; public People1() { System.out.println("父类无参构造方法!"); } public void say() { System.out.println("父类方法say()"); } public String getName() { return this.name; } public final void sayMe() { System.out.println("父类final方法sayMe()!"); } public static void main(String[] args) { People1 s=new student(12,"小明","man",100021); s.say(); String str=s.getName(); System.out.println("父类属性name:"+str); } } class student extends People1{ private int idNumber; public student() { } public void sayMe() { //不能覆盖父类中的final方法,编译器报错 System.out.println("父类final方法sayMe()!"); } public student(int a,String n,String s,int id) { age=a; name=n; sex=s; idNumber=id; System.out.println("子类含参构造方法!"); } public student(int i) { idNumber=i; System.out.println("子类含参构造方法!"); } }
3.将题目1中的people类定义为抽象类,并由student来继承
public abstract class People1 { public int age; public String name; public String sex; public People1() { System.out.println("父类无参构造方法!"); } public abstract void say(); public abstract void get() ; public static void main(String[] args) { People1 s=new student(16,"小丽","woman",12211); s.say(); s.get(); } } class student extends People1{ private int idNumber; public student() { } public void say() { System.out.println("父类方法say()"); } public void get() { System.out.println("父类属性姓名:"+name); System.out.println("父类属性年龄:"+age); System.out.println("父类属性性别:"+sex); System.out.println("子类属性学号:"+idNumber); } public student(int a,String n,String s,int id) { age=a; name=n; sex=s; idNumber=id; System.out.println("子类含参构造方法!"); } }
测试截图: