Java牛客 -- 专项练习(4)

前因:

记录在牛客上刷题的错题记事本

1. 下面属于java合法变量定义的是?

A : final
B : 1var1
C : _var2
D : var3&

答案选C, 标识符可以包括这4种字符:字母、下划线、$、数字;开头不能是数字;不能是关键字

2. 默认类型等价表示是哪一项:

public interface IService {String NAME="default";}
A : public String NAME="default";
B : public static String NAME="default";
C : public static final String NAME="default";
D : private String NAME="default";

答案选C, 接口中的变量默认是public static final 的,方法默认是public abstract 的

3. Test.main()函数执行后的输出是( )

class Test {
    public static void main(String[] args) {
        System.out.println(new B().getValue());
    }
    static class A {
        protected int value;
        public A (int v) {
            setValue(v);
        }
        public void setValue(int value) {
            this.value= value;
        }
        public int getValue() {
            try {
                value ++;
                return value;
            } finally {
                this.setValue(value);
                System.out.println(value);
            }
        }
    }
    static class B extends A {
        public B () {
            super(5);
            setValue(getValue()- 3);
        }
        public void setValue(int value) {
            super.setValue(2 * value);
        }
    }
}
A : 6 7 7
B : 22 34 17
C : 22 74 74
D : 11 17 34

答案选C。

这题比较复杂。首先理解一点:当子类调用一个方法时,若子类没有重写该方法,则再父类中寻找调用。当在调用父类方法时,又调用另一个方法,而这个方法在子类中已重写,则会调用子类的该方法。

class Parent {
    public void hi() {
        System.out.println("我是父类hi方法");
    }

    public void hello() {
        System.out.println("我是父类hello方法");
        this.hi();
    }
}

class Children extends Parent{

    @Override
    public void hi() {
        System.out.println("我是子类hi方法");
        super.hi();
    }

    Children() {
        super.hello();
    }
    
}

public class Test {
    public static void main(String[] args) {
        new Children();
    }
}

输出:

我是父类hello方法
我是子类hi方法
我是父类hi方法

其次还需理解一点:当执行try catch finally语块时,若try中有return时,还是会执行finally中代码。但是return的值不受finally中的代码影响。

public class Test2 {

    public static void main(String[] args) {
        int value = getValue();
        System.out.println(value);
    }

    public static int getValue(){
        int value = 10;
        try {
            value ++;
            return value;
        } finally {
            value *= 2;
            System.out.println(value);
        }
    }
}
22
11

当理解这两点后上面的题目接很好解决了。

4.考虑以下代码:哪些代码片段导致抛出类型为NullPointerException的对象?

String s=null;
A : if((s!=null)&(s.length()>0))
B : if((s!=null)&&(s.length()>0))
C : if((s==null)|(s.length()==0))
D : if((s==null)||(s.length()==0))

答案选A,C。

  • | : 检测ture;不具备短路功能,会检查每一个条件,表达式中只要一个ture 就整体返回true
  • || : 检测true;具备短路功能,一遇到true,就返回true;
  • & : 检测false;同理上;
  • && :检测false;同理上;
发布了15 篇原创文章 · 获赞 1 · 访问量 3128

猜你喜欢

转载自blog.csdn.net/ZeroWdd/article/details/104287715