Java类和对象习题及详细答案解析
作者:郑州吴彦祖772
废话不多说,例题:
习题一:
局部变量必须初始化:编译不能通过
习题二:
首先hello方法是一个静态成员方法(类方法)(不依赖于对象):
并且在main方法里面本来就可以直接调用,但要你非要初始化也没关系,就算是没初始化成功也没关系,毕竟静态方法不依赖于成员变量
你用引用调用(test.hello)合法但是不合理(最后你还是编译通过了)
但是如果hello没有用static修饰可就错了,毕竟你没有实例化一个对象出来
习题三:
.import static 能够导入一些静态方法
import static java . lang . Math . * ; public class Test { public static void main ( String [] args ) { double x = 30 ; double y = 40 ; // 静态导入的方式写起来更方便一些 . // double result = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) ;这样很爽,但是这样的代码要少写 double result = sqrt ( pow ( x , 2 ) + pow ( y , 2 )); System . out . println ( result ); } }
习题四:
以下代码在编译和运行过程中会出现什么情况?
会先执行构造方法,将88的值,赋值给count,所以最终输出的值是88.
public class TestDemo{ private int count; public static void main(String[] args) { TestDemo test=new TestDemo(88); System.out.println(test.count); } TestDemo(int a) { count=a; } }
习题五:
cnt的值?
答:5
public class Test{ static int cnt = 6; static{ cnt += 9; } public static void main(String[] args){ System.out.println("cnt = " + cnt); } static{ cnt /=3; }; }
本题考察的是代码块的执行顺序。带代码中存在代码块和构造方法的时候。执行顺序为:
1.静态代码块
2.实例代码块
3.调用的对应的构造方法
第2种情况:当存在相同类型的代码块和成员变量的时候,需要看定义顺序执行。
习题六:
结果?
aaabbb
class Test{ public String toString() { System.out.print("aaa"); return "bbb"; } } public static void main(String[] args) { Test test = new Test(); System.out.println(test); }
在执行println函数的时候,会调用Object类的toString方法,此时当我们自己类重新通过编译器实现了toString方法之后,会调用我们自己写的方法。
我们自己写的是返回“bbb”,先打印aaa,然后返回打印“bbb”
习题七:
结果?
答:102
public class HasStatic {// 1 private static int x = 100;// 2 public static void main(String args[]) {// 3 HasStatic hsl = new HasStatic();// 4 hsl.x++;// 5 HasStatic hs2 = new HasStatic();// 6 hs2.x++;// 7 hsl = new HasStatic();// 8 hsl.x++;// 9 HasStatic.x--;// 10 System.out.println(" x=" + x);// 11 } }
1.X是类变量,只有一份,所以说我们每次调用都会改变X的值,所有对x的操作针对的都是同一份。
2.静态成员变量的访问需要通过类名访问,这是正确的访问方式。本题中虽然使用了对象引用访问,但是不会报错,我们不建议这样访问,但不是错误,所以,不会编译报错
那大家看看这个代码结果是什么?
class Test1 { public int count; public Test1(int a){ this.count = a; } public Test1(){ } } public class Test { public static void main(String[] args) { Test1 test = new Test1(88); System.out.println(test.count); Test1 test1 = new Test1(77); System.out.println(test1.count); Test1 test2 = new Test1(); System.out.println(test2.count); } }
结果:
习题八:
编译运行的结果?
public class Pvf{ static boolean Paddy; public static void main(String args[]){ System.out.println(Paddy); } }
Passy类变量也是成员变量的默认赋值规则:
在Java当中,成员变量没有赋初值的时候,会有默认的初始值。基本类型是对应的0值。如:int是0,boolean是false,char类型是'\u0000',引用类型是null,如String。
习题九:
下述代码运行的结果是什么?
public class Test { public int aMethod(){ static int i = 0; i++; return i; } public static void main(String args[]){ Test test = new Test(); test.aMethod(); int j = test.aMethod(); System.out.println(j); } }
Java里面局部变量不能被static修饰!!!
在一个类中,在方法当中定义的变量是局部变量,而静态的变量属于类变量。随着类的加载而被创建,而局部变量是调用该方法的时候才创建的。
所以,此时两种变量的性质是冲突的。程序会报编译时异常
总结
到此这篇关于Java类和对象习题及详细答案解析的文章就介绍到这了,更多相关Java类和对象习题内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!