Java基础知识陷阱(八)

本文发表于本人博客

    这次我来说说关于&跟&&的区别,大家都知道&是位运算符,而&&是逻辑运算符,看下面代码:

    public static void main(String[] args) throws Exception {  
        int a = 1;
        int b = 2;
        int c = a & b;
        if(a >= 1 && b >= 1){
            System.out.println("&&条件1");
        }
        if(a >= 2 && (b = 3) >= 3){
            System.out.println("&&条件2");
        }
        System.out.println(b);
        System.out.println(c);        
    }

那么输出:

&&条件1
2
0

可以看出,第二个条件判断时&&进行了短路不会执行b = 3;操作。那如果把&&换成&的呢,如何,看代码:

    public static void main(String[] args) throws Exception {
        int a = 1;
        int b = 2;
        int c = a & b;
        if(a >= 1 && b >= 1){
            System.out.println("&&条件1");
        }
        if(a >= 2 && (b = 3) >= 3){
            System.out.println("&&条件2");
        }
        System.out.println(b);
        if(a >= 2 & (b = 3) >= 3){
            System.out.println("&&条件3");
        }
        System.out.println(b);
        System.out.println(c);
        
    }

看输出:

&&条件1
2
3
0

这个&符号不会产生短路功能还会进行下面的判断。

多态这个对于程序员来说是非常熟悉的了,熟悉归熟悉我还是来说说,网上也好多了,首先多态应该是一个运行时的行为,这个特别重要!网上好多地方说了重写与重载都是多态行为。但是也有些地方以及博客都会说明不要把重载理解为是多态!!

class Parent{
    public void doing(){
        System.out.println("Parent --> do");
    }
}
class Child extends Parent {
    @Override
    public void doing(){
        System.out.println("Child --> do");
    }
    public void run(){
        System.out.println("Child --> run");
    }
}

看调用代码:

    public static void main(String[] args) throws Exception {
        Parent p = new Child();
        p.doing();
        p.run();
    }

p.doing();这个是可以准确调用的,然而p.run()是编译错误,因为在父类Parent中未定义其方法,如果需要调用则需要定义为Child。

Child p = new Child();

想多理解可以看这里:

http://blog.csdn.net/cyq1028/article/details/6879088

http://www.cnblogs.com/mengdd/archive/2012/12/25/2832288.html


这次先到这里。坚持记录点点滴滴!


posted @ 2014-12-15 16:29  求 败  阅读(934)  评论(0编辑  收藏  举报