Is there a way to override class variables in Java?

后端 未结 17 1063
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:49
class Dad
{
    protected static String me = \"dad\";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    protected         


        
17条回答
  •  感情败类
    2020-11-22 10:28

    Variables don't take part in overrinding. Only methods do. A method call is resolved at runtime, that is, the decision to call a method is taken at runtime, but the variables are decided at compile time only. Hence that variable is called whose reference is used for calling and not of the runtime object.

    Take a look at following snippet:

    package com.demo;
    
    class Bike {
      int max_speed = 90;
      public void disp_speed() {
        System.out.println("Inside bike");
     }
    }
    
    public class Honda_bikes extends Bike {
      int max_speed = 150;
      public void disp_speed() {
        System.out.println("Inside Honda");
    }
    
    public static void main(String[] args) {
        Honda_bikes obj1 = new Honda_bikes();
        Bike obj2 = new Honda_bikes();
        Bike obj3 = new Bike();
    
        obj1.disp_speed();
        obj2.disp_speed();
        obj3.disp_speed();
    
        System.out.println("Max_Speed = " + obj1.max_speed);
        System.out.println("Max_Speed = " + obj2.max_speed);
        System.out.println("Max_Speed = " + obj3.max_speed);
      }
    
    }
    

    When you run the code, console will show:

    Inside Honda
    Inside Honda
    Inside bike
    
    Max_Speed = 150
    Max_Speed = 90
    Max_Speed = 90
    

提交回复
热议问题