• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Override

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
/*code snippet from Vehicle.java*/

public abstract class Vehicle{

public abstract String getName();

public Class dataClass = Axle.class;


public void printClassName(){
System.out.println("Class Name: " + dataClass);
}

}

/*code snippet from Car.java*/

public class Car extends Vehicle{


public Class dataClass = LicensePlate.class;

public String getName(){
return "Mustang";
}

public static void main(String a[]){

Car car = new Car();
System.out.println(car.getName());
car.printClassName();

}
}

Provided the classes Axle and LicensePlate are present, why is it that the output is Axle.class and not LicensePlate.class which i thought would override the super class' Class attribute dataClass since it has public access.

thanks in advance
- Kalyan
 
Kalyan Dasika
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(this is the output)

Mustang
Class Name: class com.dasika.domain.Axle
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
instance variables can hide other variables but only instance methods can override anything.

variable references are resolved at compile time, when class Vehicle knows nothing about subclass Car. method Vehicle.printClassName() has a reference to variable dataClass. In order of preference, this will be satisfied by:
1. a local variable dataClass
2. an instance variable dataClass declared in class Vehicle
3. an inherited instance variable dataClass declared in a superclass of class Vehicle

If the only declaration of dataClass was in subclass Car, class Vehicle would have a compilation error.
 
reply
    Bookmark Topic Watch Topic
  • New Topic