问答详情
源自:10-1 Java 中的多态

java中通过父类引用创建子类对象后,输出子类的属性值不是子类中所写的属性值,而是继承父类的,为什么

package com.hu; 

public class Vehicle {
   public int num;   
   public String mode;   
   public String type; 
         
   public void ability(){ 
          System.out.println("交通工具具有载人出行的能力");                
          System.out.println("num:"+num+"\nmode:"+mode+"\ntype:"+type);            
          }        
  }   
                
public class Car extends Vehicle { 
   public int num=6;     
   public String mode="陆行";      
   public String type="汽车";  
           
   public void ability(){
               System.out.println("汽车具有载人陆行的能力");                  
               System.out.println("num:"+num+"\nmode"+mode+"\ntype"+type);                
               }                    
               @Override                        
               public String toString() {                        
               return "Car [num=" + num + ", mode=" + mode + ", type=" + type + "]";                        
               } 
               
               public class Initail {   public static void main(String[] args) { 
                              Vehicle vehicle = new Vehicle();                
                              Vehicle car = new Car();  
                                                                            
                               vehicle.ability();                  
                               System.out.println();   
                                                                    
                               car.ability();                  
                               System.out.println();                                    
                               System.out.println(car.num+"\n"+car.mode+"\n"+car.type);//就是这行
                                               
                               System.out.println();                                                    
                               System.out.println(car);                        
                               }                
                               }

为什么

System.out.println(car.num+"\n"+car.mode+"\n"+car.type);

这句输出的是

0

null

null

而不是

6

陆行

汽车


提问者:Hu丶0403 2018-04-25 21:28

个回答

  • oldCattt
    2018-05-15 09:48:02
    已采纳

    父类引用指向子类对象的时候,只有调用方法的时候,得到的才是子类重写的方法,所以你的car.ability();输出的是正确的,但是car.num这样直接调用变量是不行的

  • 慕雪6270127
    2018-07-20 11:42:31

    你的属性应该写在方法里

  • qq_久未见你未变_0
    2018-07-19 20:37:35

    https://img.mukewang.com/5b50848b00010f3c10170534.jpg

    https://img2.mukewang.com/5b5084c10001b32806760342.jpg

    https://img4.mukewang.com/5b5084e80001a34006710529.jpg

    我想应该是这样的:父类和子类有同名的属性时,子类的属性并不会覆盖父类的属性,使用父类引用输出属性值,输出的是父类的。而方法不同,方法会覆盖父类方法。

  • qq_seeyouagain_35
    2018-07-01 15:45:40

    阔以  的



  • 慕哥8419319
    2018-04-25 22:03:06

    keyi