- 1.内层的变量可以访问外层的变量,外层的无法访问内层的变量
public class Scope {public static void main(String[] args) {
int x = 1;
{
int y = 2;
}
{
int z = 3;
}
}
}
以上例子中,第三行x可以访问x,第五行y可以访问y,x,第九行z可以访问z,y,x;
- 有static的都属于类。没有static修饰符的属于实例方法
import java.util.Arrays;
public class Argument {
static void doubleBasic(int x){ //有static的都属于类。没有static修饰符的属于实例方法
x*=2;
}
static void doubleReference(int[] a){
for(int i=0;i<a.length;i++){
a[i]*=2;
}
}
public static void main(String[] args) {
int x=10;
doubleBasic(x);
System.out.println(x);
int[] a={1,2,3};
doubleReference(a);
System.out.println(Arrays.toString(a));
}
}
以上例中,doubleBasic调用的x为第十五行复制给的值(即两个x无关联),所以第五行x乘以2后也不会原来x的值也不会变;
而第20行中数组a(即int[] a)储存的是数组a代表的地址,所以doubleReference调用的a中也为数组a的地址(即指向同一地址),所以数组a中的数字经过第10行执行后会变成原来的两倍。
- 任何一个实例方法的内部,都有一个隐式参数this;
this代表调用这个实例方法的对象(谁调用这个实例方法,this就代表谁)
注意的是:静态方法中没有this,静态方法内部无法直接访问实例字段和实例方法
//此代码中会调用Card.java中的对象
class BadIcCard{
long id;
double money;
void show(){
System.out.printf("id: %d , money: %.2f\n",id,money);
}
void add(double money){
this.money+=money; //this在此处,代表此处引用this
}
}
public class Shadowing {
public static void main(String[] args) {
BadIcCard card=new BadIcCard();
card.id=1001;
card.money=1000;
card.add(100);
}
}
- 方法名,参数的个数,参数的类型构成了方法的签名
方法的返回值类型/参数的名字 不属于方法的签名
//例a
int add(int x,int y);
int add(int a,int b);
//例b
int add(int x,int y);
void add(int a,int b);
以上两个例子(例a,例b)中,表示相同的方法(与参数的名字,方法的返回值无关)
//例c
int add(int x,int y,int z);
例c中,因为参数的个数不同,所以此add方法与上两个(例a,例b)不同
//例d
int test(int a,String s);
int test(String s,int a);
例d中,因为类型不同,所以方法不同
方法的重载:方法名相同,但方法的签名不同,这些方法可以同时存在 (参数列表不同)
class Rectangle{
int getArea(int w,int h){ //方法a
return w*h;
}
double getArea(double w,double h){ //方法b
return w*h;
}
}
public class OverLoading {
public static void main(String[] args) {
Rectangle rectangle=new Rectangle();
rectangle.getArea(3,2);//此处调用方法a
rectangle.getArea(3.0,2.0); //此处调用方法b
rectangle.getArea(3,2.0); //此处调用方法b
}
}
- 构造器:
(1)访问修饰符一般都是public
(2)与类同名
(3)不能有返回类型
快捷键:Alt+Insert➡构造函数
下面为一个构造器
public Rectangle{
}
- 一般地,字段都使用private修饰符
private类内可见,默认修饰符(无)包内可见,
protected 包内或子类内可见,public 处处可见
私有字段通过公有的访问器(getter)来访问,通过公有的修改器(setter)来修改。
访问器的修饰符是public,类型与字段一致,名字是get跟上字段名
修改器的修饰符是public,一定是没有类型的,名字是set跟上字段名
public class Rectangle {
double width;
double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
//以下为访问器
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
//以下为修改器
public void setWidth(double newWidth) {
width = newWidth;
}
public void setHeight(double newHeight) {
height = newHeight;
}
}
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://ntvu.love/?p=88