1.Java中有虚函数,但是没指针,那也许会有这样的问题,那java是怎么实现多态的?
java中可以肯定是有虚函数的,而且我们假如不申明为final形他默认就是虚函数.不用vitual申明.
"In Java, you do not need to declare a method as virtual. Dynamic binding is the default behavior. If you do not want a method to be virtual, you tag it as final"--from <core java2 :volum I>.
java中没显示的和c++中的指针,但是他有地址的概念的.而且所有我们申明的"对象"其实就是地址(或叫句柄),给他赋值就是把他指向一个内存单元.当然也可以改变他的指向.其实我们"对象"的赋值操作全是地址在变东,对象还是没有变的.那也许有人会说那样的话不是会产生很多没有"对象"(句柄)的内存区域.是的是会产生,但是java的垃圾收集机制会给我们回收这样的内存"泄漏".所以我们只关心我们操作的对象就行,其他的我们不用的对象的后事垃圾收集会给我们干.
明白了在java中的"对象"而非我们c++中理解的对象.而实际上是指针(句柄)那多态当然可以实现.
下面举个"对象"赋值(引用)的例子说明,全是地址在变,而非真的内存单元.
public class Number {
private int number;
public Number( int number ) {
this.number = number;
}
public int getNumber() {
return this.number;
}
public void setNumber( int number ) {
this.number = number;
}
public static void main( String[] args ) {
Number one = new Number( 1 );
Number two = new Number( 2 );
System.out.println( "Beginning: " );
System.out.println( "One = " + one.getNumber() );
System.out.println( "Two = " + two.getNumber() );
// Assign two to one
two = one;//在这里two这个句柄的值(即某个对象的地址)改成one这个句柄的值了.从而two和one指同时//向one以前指向的那个内存单元(对象).而two 以前指向的那个对象现在为没有句柄连接的对象了.可能要被垃圾收集
System.out.println( "\nAfter assigning two to one: " );
System.out.println( "One = " + one.getNumber() );
System.out.println( "Two = " + two.getNumber() );
// Change the value of two
two.setNumber( 3 );//two和one指向同一个单元,所以他对改单元的改变,one能感知.
System.out.println( "\nAfter modifying two: " );
System.out.println( "One = " + one.getNumber() );
System.out.println( "Two = " + two.getNumber() );
}
}
运行结果:
Beginning:
One = 1
Two = 2
After assigning two to one:
One = 1
Two = 1
After modifying two:
One = 3
Two = 3
Press any key to continue...
java新手和学习c++的一点感受,如有不对之处,还望指出.