Your code in the InheritanceExample class needs to be inside the main method for it to run as you want it. Wrap up all the code inside the InheritanceExample class inside a main as shown below:-
public class InheritanceExample {
public static void main(String[] args) { //-> My Addition
Car a=new Car();
Guzzler g=new Guzzler();
a.drive(100);
g.drive(200);
System.out.println("Car mileage : "+c.odometer);
System.out.println("Guzzler mileage : "+g.odometer);
g.guzzle();
if(g instanceof Car)
{
System.out.println("Guzzler is a car!!!");
}
} //--> My Addition
} Here is a tutorial on the structure of a basic Java program.
Also another note on the code inside your Car constructor:-
public Car(){
int odometer=0;
System.out.println("Car constructed!");
} The above chunk of code does not initialize the "odometer" attribute of the Car class, instead it just declares another local variable by the same name and sets it to '0'. The only reason why this hasn't caused a problem is cause Java initializes class level variables to some assumed defaults, example 'int', 'long' are initialized to '0', Object references to null and so on
stephen84s
Nearly a Posting Virtuoso
1,443 posts since Jul 2007
Reputation Points: 668
Solved Threads: 154