类和对象的概念
实例变量
⽅法重载
构造⽅法
引⽤的概念
this关键字
习题:
1,重载,实例变量
有以下代码:
class ClassA{
public void method(int value){
System .out .println(value);
}
public void method(){
System .out .println(value);
}
int value ;
}
class TestClassA{
public static void main(String args[]){
ClassA classA = new ClassA();
classA .value = 10 ;
classA .method();
classA .method(20);
}
}
请选择正确结果:
A. 编译不通过
B. 输出10 10
C. 输出 10 20
D. 输出0 20
答案:C
2,方法重载,函数返回值
有以下代码:
class ClassA{
void method(){
System .out .println("method()");
}
int method(int i){
System .out .println("method(int)");..
}
ClassA a = new ClassA(); a .method();
a .method(10);
}
}
该程序是否能编译通过?
如果可以,写出该程序运⾏结果。
如果不能,请说明理由,以及如何修改。
答案: 不能通过编译
因为,int method(int)方法没有返回值,需要添加相应的return语句
缺少返回语句return i;
3,构造⽅法
关于构造⽅法,下列说法正确的是:
A. 每个类中都有⾄少⼀个构造⽅法
B. ⼀个类中可以有多个构造⽅法
C. 构造⽅法可以有返回值