-8

I've overridden a method and tried to access the overridden method but,the compiler says like"non-static variable super can not be referenced from a static content".

I tried calling the overridden method in the constructor of the sub class, well it worked fine but, i wanna access it outside of the constructor.

class vehicle{
    static String name;
    static int model;
    static int price;
    static String station;
    public vehicle(){
        model=220;
        name="Ducati";
        price=500000;
        station="London";       
    }
    public static void display(){
        System.out.println("Name of the vehicle: "+name+"\nmodel: "+model+"\nprice: ```"+price+"\nservice station: "+station);
    }
}
class bike extends vehicle{
    static double rate;
    public bike(){
        rate=0.25;      
    }
    public static void display(){
        System.out.println("Vehicle name: "+name+"\nmodel number: "+model+"\ncost: "+price+"\nservice station: "+station+"\n discount rate: "+rate);
    }
    public void discount(){
        double rate2=price*rate;
        double rate3=price-rate2;
        System.out.println("Discount rate of the bike is "+rate3);
    }
    public static void main(String args[]){
        bike bee=new bike();
        super.display();
        display();
        bee.discount();
   }
}

i wanna know why i can't access the shadowed method in the specified place of my code

Anshu
  • 1,277
  • 2
  • 13
  • 28
Trouble Maker
  • 99
  • 1
  • 5
  • `static` variables are not instance variables. `super.display()` makes no sense in a `main` method; did you want to call `bee.display();`? Or did you want to call `vehicle.display();`? Class names start with a capital letter in Java; your code is very difficult to read. – Elliott Frisch Jul 09 '19 at 04:10
  • i want to call vehicle.display(); can you please explain me why is this happening ? And i'm a beginner also i'm trying to write the neat code – Trouble Maker Jul 09 '19 at 04:15
  • This is not neat code. Call `vehicle.display()` then. `super` is for constructors and instance methods. Not `main` (or `static` methods). **Don't** make everything `static`. – Elliott Frisch Jul 09 '19 at 04:16
  • bro i meant i'm trying to write neat code, but we also use the "super" to access the shadowed things right? – Trouble Maker Jul 09 '19 at 04:20
  • code is unreadable: \` is not allowed; missing indentation at all (if you post code like that, I don't want to see how you code if not intended for someone (else) to see) – user85421 Jul 09 '19 at 04:58
  • and I do not believe that `static` methods can be overridden at all: [8.4.8.1. Overriding (by Instance Methods)](https://docs.oracle.com/javase/specs/jls/se12/html/jls-8.html#jls-8.4.8.1) at most they are hidden – user85421 Jul 09 '19 at 05:09

1 Answers1

0

super is not allowed for static method or constructors. You can make the method not static then you can call it.