java 类 关键字_Java类中的常用关键字介绍

public class Bicycle {

private int cadence; //field

private int gear;

private int speed;

static final int test = 1;

public Bicycle(int startCadence, int startSpeed, int startGear) {

gear = startGear;

cadence = startCadence;

speed = startSpeed;

} //这是一个构造函数,注意构造函数与成员方法不同,不需要声明返回值。

//且与Class名同名。

public int getCadence() {

return cadence;

}

public void setCadence(int newValue) {

cadence = newValue; //当没有返回值时用void,且不需要return语句。

} //成员方法必须声明返回值类型,或是void

}

1,class前可以使用modifiler:public and no modifiler (package private).

members前可以使用modifiler:public, private, protected and no modifiler.

这些modifiler控制的是从其他地方访问类或members的access权限,分为:从class本身,从本class所在的package中的其他class,从其他package中的subclass,从其他地方。

详细介绍见链接:

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

2,this关键字

由上例可见,this.x是对成员变量的引用,this()是对constructor的引用。

public class Rectangle {

private int x, y;

private int width, height;

public Rectangle() {

this(0, 0, 1, 1);

}

public Rectangle(int width, int height) {

this(0, 0, width, height);

}

public Rectangle(int x, int y, int width, int height) {

this.x = x;

this.y = y;

this.width = width;

this.height = height;

}

...

}

3,static 关键字

field前可以使用static关键字,该关键字意味着:这个field不在属于object,而是属于class。这样的变量不再属于各个实例化的对象,而是被这些对象所共有,在内存中使用一个空间。由于static field属于class,因此不实例化类就可以直接使用它,同时实例化出来的所有object也都可以使用它。

method前也可以使用static,且也可以不实例化即可直接引用:className.memberName(); or objectName.memberName();

通常用static methods访问static fields。

4, static + final

static final int test = 1;则定义了一个常量constant。这样test的值不允许被修改。

5, method signature

同一class中的多个method方法名可以重复,只要parameter的类型或者个数不同即可(parameter 名字不同步行),method name + parameters成为method signature。plus, 只是return type不同,并不能区分method。

6, constructor

构造函数,通常是public的。constructor可以有多个,只要method signature不同即可。也可以使用父类的constructor。如果没有提供contructor,complier会提供一个默认的,无参数的constructor。

7, Method的返回值

public Number returnANumber() {

return this.number;

}

method中用return 关键字指定method的返回值。method的返回值通常是int,string这样的primitive type,也可以无返回值void。当method的return type不是primitive type,而是自定义的class时(如上例中的Number),method返回的value可以是一个Number对象,或是Number类的子类的对象。

return type也可以是一个interface,这时method返回值必须是实现了该接口的对象。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值