Java变量阴影方法被覆盖的概念 [英] Java Variables Shadowed Methods overridden concept

查看:116
本文介绍了Java变量阴影方法被覆盖的概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力理解使用Java继承的Variables Shadowed Methods Overriden概念。

I am struggling to understand Variables Shadowed Methods Overriden Concept of inheritance with Java.

案例1:

class Car{
   public int gearRatio = 8;
   public String accelerate() {  return "Accelerate : Car";  }
}
class SportsCar extends Car{
   public int gearRatio = 9;
   public String accelerate() {  return  "Accelerate : SportsCar";  }
   public static void main(String[] args){
      Car c = new SportsCar();
      System.out.println( c.gearRatio+"  "+c.accelerate() );
   }
}

输出:8加速:Sportscar。

Output: 8 Accelerate : Sportscar.

案例2:

public class TestClass{
   public static void main(String args[ ] ){
      A o1 = new C( );
      B o2 = (B) o1;
      System.out.println(o1.m1( ) );
      System.out.println(o2.i );
   }
}
class A { int i = 10;  int m1( ) { return i; } }
class B extends A { int i = 20;  int m1() { return i; } }
class C extends B { int i = 30;  int m1() { return i; } }

输出:30,20

因此,如果我理解正确,除非明确调用子类变量,否则始终调用超类变量。但是对于调用子类重写方法的方法则相反,除非显式调用超类。

So if I understand correctly, the super class variable is always called unless the sub classes variable is called explicitly. But the opposite is true for methods where the sub classes overridden method is called unless the super class is called explicitly.

我认为变量和方法应该在相同或那里工作在创建具有相同变量的子类时应该是编译错误。

I would think variables and methods should work the same or there should be a compile error when creating sub classes with the same variables.

有人可以解释这是否正确以及为什么java会像这样工作。

Can someone explain if this is correct and why java works like this please.

推荐答案


我认为变量和方法应该相同,或者在创建具有相同变量的子类时应该存在编译错误。

I would think variables and methods should work the same or there should be a compile error when creating sub classes with the same variables.

嗯,这根本不是Java的工作方式。

Well, that's simply not the way Java works.

变量处理多态 - 有没有覆盖变量的概念。但是,的方法以多态方式处理。 行为可以是专门的,但不是

Variables are not handled polymorphically - there's no concept of "overriding" a variable. Methods, however, are handled polymorphically. Behaviour can be specialized, but not state.

请注意,如果您的变量是私有的,因为它们几乎总是应该是,情况永远不可见。

Note that if your variables are private, as they almost always should be, the situation is never even visible.

这篇关于Java变量阴影方法被覆盖的概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆