+ 1
How to make an object in a class of another class while both being in the same package?
So i have a main class, with a main method. For simplicity call them Project.java, class Project and main. And then i have a package, and 2 classes in it, for example Car.java with class Car, class Wheel class Radio etc. and Horn.java with class Horn. How to create a Horn object in class Car?
3 Respostas
+ 2
For the first you need to create an object of Car in your main method
then you can create an object of Horn in class Car
public class Main{
public static void main(String args[]) {
Car c = new Car();
c.carMethod ();
}
}
public class Car {
public void carMethod () {
Horn h = new Horn(); //creating an object of Horn
//use the reference variable (h) to call your method
h.myHornMethod();
}
}
public class Horn {
public void myHornMethod() {
System.out.println("text");
}
}
But if your class is in another package you need to import your class from your Main class like this:
import PackageName.YourClassName;
+ 2
You are welcome:)
+ 1
So i just need to put the horn object initialization in a method. Thank you very much!