跟着官方文档学Java_jdk1.8_(4)——系列

接续上一篇跟着官方文档学Java_jdk1.8_(3)——系列https://blog.csdn.net/qq_38382925/article/details/113194386

先写一个自行车类,这个类中含有各种自行车的共性。
如,Bicycle类提供了三个变量(域),一个构造器,四个方法。

public class Bicycle {
        
    // the Bicycle class has
    // three fields
    public int cadence;
    public int gear;
    public int speed;
        
    // the Bicycle class has
    // one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }
        
    // the Bicycle class has
    // four methods
    public void setCadence(int newValue) {
        cadence = newValue;
    }
        
    public void setGear(int newValue) {
        gear = newValue;
    }
        
    public void applyBrake(int decrement) {
        speed -= decrement;
    }
        
    public void speedUp(int increment) {
        speed += increment;
    }
        
}

MountainBike作为一个子类。继承了父类Bicycle。
MountainBike有一个属性,setHeight。一个构造器。一个方法。

public class MountainBike extends Bicycle {
        
    // the MountainBike subclass has
    // one field
    public int seatHeight;

    // the MountainBike subclass has
    // one constructor
    public MountainBike(int startHeight, int startCadence,
                        int startSpeed, int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;
    }   
        
    // the MountainBike subclass has
    // one method
    public void setHeight(int newValue) {
        seatHeight = newValue;
    }   

}

子类继承了父类的所有属性和方法。(因为这个父类的所有属性和方法都是公共的。)

申明一个类

一个类的定义和内容如下:
关键字:class
域,构造器,方法申明

class MyClass {
    // field, constructor, and 
    // method declarations
}

构造器,是为了初始化新对象。申明域

一个类可以同时实现和继承一个父类,如:

class MyClass extends MySuperClass implements YourInterFace {
	//field, constructor, and method declarations
}

申明成员变量

有三种变量:

  1. 类中的成员变量——fields
  2. 方法或代码块中的变量——局部变量
  3. 方法声明中的变量——参数

访问控制

对象

内部类

枚举类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值