1.关键字extends
2.Java中只能单继承不能多继承。
3.Object类是所有类的父类。
4.代码测试及运行截图
父类:
package day_03oop_test;
public class Circle {
private double radius;
//计算圆的面积
public double findArea() {
return Math.PI*radius*radius;
}
//set和get方法
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
子类:
package day_03oop_test;
public class Cyclinder extends Circle {
private double height;
//set和get方法
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
//计算圆柱的体积
public double findVolume() {
return findArea()*getHeight();
}
}
测试类:
package day_03oop_test;
public class CyclinderTest {
public static void main(String[] args) {
Cyclinder cy = new Cyclinder();
cy.setHeight(2.5);
cy.setRadius(2.9);
System.out.println("圆的面积是:" + cy.findArea());
System.out.println("圆柱的体积是:" + cy.findVolume());
}
}
/*感悟:每个类中都默认存在一个无参构造器,如果重新写构造器如果带参,则覆盖掉原无参构造器。
* 这时候如果要用new 类名(),则报错。因为不存在无参构造器。所以一般情况最好写两个构造器,
* 一个无参,一个有参。*/
5.属性一般用private体现封装性(只在本类可见,无法被继承),方法一般用public让子类继承,体现继承性。
6.super表示父类的XXXX
7.关于super关键字的使用
父类:
package day_06_SuperTest;
public class Person {
int id = 1;
public void eat() {
System.out.println("我可以吃Person");
}
public void show() {
System.out.println(id);
}
}
子类:
package day_06_SuperTest;
public class Student extends Person{
int id = 1000000;
public Student() {
super.eat();
}
public void eat() {
System.out.println("我可以吃student");
//调用父类同名方法
super.eat();
}
public void show() {
System.out.println(this.id);
System.out.println(super.id);
System.out.println(id);
//属性不存在覆盖,调用当前类的属性。
}
}
测试类:
package day_06_SuperTest;
public class StudentSuper {
public static void main(String []args) {
Student st = new Student();//调用构造器
// st.eat();
// st.show();
/*1.场景:在子类中需要使用从父类中继承的方法,但是该方法已经被重写,
此时直接调方法,调用的是子类重写的方法,要想使用原先父类中的方法此时需要super关键字
2.super理解成父类的。。。可以调用方法、属性、构造器
3.使用:(1)super.属性
(2)super.方法名()
(3)super(参数)构造器*/
}
}
8.this,super必须在方法体或构造器的第一行
9.重写只对于非静态方法来说的
10.参数列表和方法名必须相同,修饰符子类的范围必须>=父类