Java与c++区别(陆续更新)

一、对于子父类转换
使用父类类型引用一个子类,当使用两者都有的某一方法时:

调用该对象的某一个方法 Java会使用子类的方法,c++会使用父类的方法
c++:

实例代码(转自https://www.cnblogs.com/cxq0017/p/6074247.html)
 
1#include "stdafx.h"
 2 #include <iostream> 
 3 #include <stdlib.h>
 4 using namespace std; 
 5 
 6 class Father
 7 {
 8 public:
 9     void Face()
10     {
11         cout << "Father's face" << endl;
12     }
13 
14     void Say()
15     {
16         cout << "Father say hello" << endl;
17     }
18 };
19 
20 
21 class Son:public Father
22 {
23 public:     
24     void Say()
25     {
26         cout << "Son say hello" << endl;
27     }
28 };
29 
30 void main()
31 {
32     Son son;
33     Father *pFather=&son; // 隐式类型转换
34     pFather->Say();
35 }


结果:father say hello

原因: 我们构造Son类的对象时,首先要调用Father类的构造函数去构造Father类的对象,然后才调用Son类的构造函数完成自身部分的构造,从而拼接出一个完整的Son类对象。当我们将Son类对象转换为Father类型时,该对象就被认为是原对象整个内存模型的上半部分,也就是上图中“Father的对象所占内存”,那么当我们利用类型转换后的对象指针去调用它的方法时,当然也就是调用它所在的内存中的方法,因此,输出“Father Say hello”,也就顺理成章了。
而Java中:(来自:https://blog.csdn.net/kaiwii/article/details/8042488)

 
class Animal{
   public int age;
   public void move(){
      System.out.println("动物可以移动");
   }
}
 
class Dog extends Animal{
   public double age;
   public void move(){
       age = 10.00;
      System.out.println("狗可以跑和走");
   }
   public void bark(){
      System.out.println("狗可以吠叫");
   }
}

class Cat extends Animal{
   public void move(){
       super.age = 3;
      System.out.println("猫可以跳");
   }
}
 
public class TestOverride{
   public static void main(String args[]){
      Animal a = new Animal(); // Animal 对象
      Animal b = new Dog(); // Dog 对象
      Dog c = new Dog();
      Cat d = new Cat();
      
      a.move();// 执行 Animal 类的方法
      b.move();//执行 Dog 类的方法
      c.move();//执行 Dog 类的方法
      d.move();//执行 Cat 类的方法
      Object aValue = a.age;
      Object bValue = b.age;
      Object cValue = c.age;
      System.out.println("The type of "+a.age+" is "+(aValue instanceof Double ? "double" : (aValue instanceof Integer ? "int" : "")));
      System.out.println("The type of "+b.age+" is "+(bValue instanceof Double ? "double" : (bValue instanceof Integer ? "int" : "")));
      System.out.println("The type of "+c.age+" is "+(cValue instanceof Double ? "double" : (cValue instanceof Integer ? "int" : "")));// 覆盖age属性
      System.out.println("The age of cat  is "+d.age);
     
   }
}

编译值:

动物可以移动
狗可以跑和走
狗可以跑和走
猫可以跳
The type of 0 is int
The type of 0 is int
The type of 10.0 is double
The age of cat  is 3
 
java 中可以总结以下几点:

1、使用父类类型的引用指向子类的对象;

2、该引用只能调用父类中定义的方法和变量;

3、如果子类中重写了父类中的一个方法,那么在调用这个方法的时候,将会调用子类中的这个方法;(动态连接、动态调用);

4、变量不能被重写(覆盖),"重写"的概念只针对方法,如果在子类中"重写"了父类中的变量,那么在编译时会报错。



如上 Java会使用子类的方法,c++会使用父类的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值