I am new to Java.This was a example on OOP.I have a class file named "Automobile.java" and the driver program saved as AutomobileTest.java.My question is when a object is created in AutomobileTest.java how does it know that it has to access the methods and variables from Automobile.java.
This is my code:
Automobile.java
class Automobile{
public int numWheels;
public String colour;
public boolean engineRunning;
public double mileage;
public int numSeats;
public Automobile(int wheels,int seats,String vehicleColour){
numWheels=wheels;
numSeats=seats;
colour=vehicleColour;
engineRunning=false;
mileage=0.0;
}
public void startEngine(){
engineRunning=true;
}
public void stopEngine(){
engineRunning=false;
}
public double drive(double numMiles){
return mileage+=numMiles;
}
public String toString(){
String s="numWheels="+numWheels+"\nNumber of seats = "+numSeats+ "\nColour:" +colour+ "\nEngineRunning: " + engineRunning;
return s;
}
}
AutomobileTest.java
public class AutomobileTest{
public static void main (String args[]){
Automobile ferrari=new Automobile(4,2,"red");
System.out.println(ferrari);
System.out.println("Engine started");
ferrari.startEngine();
System.out.println(ferrari);
}
}
4 Answers 4
From your question I totally understand that you are new to Java programming.
To answer your question, in the AutomobileTest.java file, you have included the statement
Automobile ferrari=new Automobile(4,2,"red");
in this line, the keyword "new" will tell the java compiler to create a object of the class Automobile and thus java compiler will know which class to access.
To know more about this, you need to do a lot of study. Refer this book.
Comments
If you are asking how the contents of AutomobileTest.java knows to find the Automobile class in Automobile.java, this has to do with Java packaging.
In Java, you can declare classes to be of a certain package by saying package X at the top of multiple Java source files. This means that they will share a "namespace", and thus have access to methods and variables (subject the access modifiers that other commenters are mentioning, such as public and private).
But it seems like your files don't say package X at the top. Well, by default Java puts files in the same directory in the "anonymous package", so technically Automobile.java and AutomobileTest.java share a namespace.
For more information about Java packages, see these resources: http://en.wikipedia.org/wiki/Java_package http://docs.oracle.com/javase/tutorial/java/package/packages.html
Comments
Have a look at this question: In Java, difference between default, public, protected, and private
Modifier | Class | Package | Subclass | World
————————————+———————+—————————+——————————+———————
public | ✔ | ✔ | ✔ | ✔
————————————+———————+—————————+——————————+———————
protected | ✔ | ✔ | ✔ | ✘
————————————+———————+—————————+——————————+———————
no modifier | ✔ | ✔ | ✘ | ✘
————————————+———————+—————————+——————————+———————
private | ✔ | ✘ | ✘ | ✘
Automobile class)