题目

代码:

package test;

public class Java4 {
    public static void main(String[] args) {
        double Perimeter, Area, Vol,;

        Circle c = new Circle(2);

        System.out.println("圆的半径是:"+c.getRadius());
        System.out.println("圆的周长是:"+c.getPerimeter());
        System.out.println("圆的面积是:"+c.getArea());

        Cylinder cy = new Cylinder(2, 4);
        System.out.println("圆柱体的高是:"+cy.getHeight());
        System.out.println("圆柱体的体积是:" + cy.getVol());

    }
   static class Circle{
        double PI = 3.14159265358979323846;
        double radius;  //圆的半径

        Circle(){  //把半径设置为零
            this.radius = 0;
        }

        Circle(double r){  //创建对象时把半径初始化为r
           radius = r;
        }

        double getRadius() {  //半径
            return radius;
        }

        double getPerimeter(){   //圆的周长
            return 2*radius*PI;
        }
        double getArea() {  //圆的面积
            return PI*radius*radius;
        }

    }
    static class Cylinder extends Circle {
        double height;

        Cylinder(double r, double h) {
            this.radius = r;
            this.height = h;
        }

        public double getHeight() {  //获取圆柱体的高
            return this.height;
        }

        public double getVol() {   //圆柱体的体积
            return PI * radius * radius * height;
        }
    }
}

运行截图:

有遇到一些问题来着例如:

错误提示是:无法从静态上下文中引用非静态 变量 this

因为没有好好的理解这句话----“静态方法中不能引用非静态变量”,把Cylinder类和Circle类嵌套定义在Test类中了----
想要解决这个问题有两种方法:

  1. 把它们从Test类中划出来

  2. 把它们也定义为静态类

此处我用的是第二种方法,第一种我还不会怎么使用😂

课堂学习总结以及自学总结:

构造函数:

public 类名称(){

调用时直接new一个对象(也就是创造新的对象)

例如:

public person () {
    System.out.println(“构造方法执行!”)
}

在main的类下来上一串代码

Person one = new person();

Arrays数组

例如:

//String—>数组
String str  = “jdviufvndsnvweoi”;
Char[] chars = str.tocharArray();

Arrays.sort方法,必须是一个数组才可以使用

继承

继承关系当中的特点:

  1. 子类可以拥有父类的“内容”
  2. 子类还可以拥有自己专属的内容

格式:

public class 父类名称{

}
Public class 子类名称 extends 父类名称{
	 
}

区分子类方法中重名的三种:

局部变量:直接写成员变量名
本类的成员变量: this.成员变量名
父类的变量名: super.成员变量名

继承中成员方法的访问特征:

创建的对象是谁,就优先用谁,如果没有则向上找

注意:

无论是成员方法还是成员变量。如果没有就向上找父类,绝对不会向下找子类的。

重写(覆写,覆盖)与重载的区别:

重写(Override): 方法名称一样,参数列表【也一样】。
重载(Overload): 方法名称一样,参数列表【不一样】。

方法的覆盖重写特点:创建的是子类对象,在优先使用子类方法

 posted on 2019-10-06 15:41  怪她  阅读(126)  评论(0编辑  收藏  举报