Java: using object from class in another class - java

I have two different files. In the file below I create a new object with an attribute and I create a method to retrieve that attribute.
public class Journey
{
public double singleCost;
public void setSingleCost(double cost) {
singleCost = cost;
}
public double getSingleCost() {
return singleCost;
}
public static void main (String[] args) {
Journey leicester_loughborough = new Journey();
leicester_loughborough.setSingleCost(2.5);
Journey leicester_nottingham = new Journey();
leicester_nottingham.setSingleCost(3.5);
}
}
In a separate file, I would like to print out that object's attribute. I'm not sure how to do that though. The following doesn't seem to work.
public class JourneyMethods
{
public static void main (String[] args) {
System.out.println(leicester_loughborough.getSingleCost());
}
}
I would appreciate any help, thanks.

You are thinking about this too much as main methods.
Your JourneyMethods main method knows nothing about the Journey class unless you tell it. JourneyMethods will be able to interact with a Journey instance if you create a reference to a Journey.

Your class object :
public class Journey
{
public double singleCost;
public void setSingleCost(double cost) {
singleCost = cost;
}
public double getSingleCost() {
return singleCost;
}
}
Your main class :
public class JourneyMethods
{
public static void main (String[] args) {
Journey Leicester_loughborough = new Journey();
leicester_loughborough.setSingleCost(2.5);
Journey leicester_nottingham = new Journey();
leicester_nottingham.setSingleCost(3.5);
System.out.println(leicester_loughborough.getSingleCost());
}
}
This is how Java works, I think that you are confused with C (with .h and .c files)
Having a main() function in your Journey class does not make sense, you can instantiate your object from anywhere in your code, so have it in your main() function :)
In Java, you generally want to put methods in the Object class.

You simply create a getter()-method for the attribute you want to have in the class that has it (in your case Journey.class).
Like this:
public double getSingleCost() {
return singleCost;
}
You can then get the attribute by calling the getSingleCost() from the object-instance you have. Like this:
double cost = leicester_loughborough.getSingleCost();
Please note that this is really basic stuff and you might want to read some more Java tutorials first.
Oh, and your program is only supposed to have one main() method as entry point. (there are reasons to have more than one but those are very case-specific). If you run your program in the way it's written in the OP, the address spaces as well as the execution of the two applications are seperated from each other and you do not have a means to access objects that are contained in a different application (well, there are ways like serialization, but those are more advanced topics).
Have your classes/objects contained in the same program.
Edit: Fixing OP's code to work as intended:
public class Journey
{
public double singleCost;
public void setSingleCost(double cost) {
singleCost = cost;
}
public double getSingleCost() {
return singleCost;
}
}
JourneyMethods:
public class JourneyMethods
{
public static void main (String[] args) {
Journey leicester_loughborough = new Journey();
leicester_loughborough.setSingleCost(3.5);
System.out.println(leicester_loughborough.getSingleCost());
}
}
You need to create the two journey objects in your JourneyMethods class so you have a reference to them. Also you should refer to the 'files' as classes, because 'file' usually implies files on the filesystem, not files representing Java classes. That confused me a bit.

To access the object attributes, you have to make the objects in the external class and use getter and setter methods to get the values of the objects.
public class Journey{
public double singleCost;
public void setSingleCost(double cost) {
singleCost = cost;
}
public double getSingleCost() {
return singleCost;
}
}
public class JourneyMethods{
public static void main (String[] args) {
Journey Leicester_loughborough = new Journey();
leicester_loughborough.setSingleCost(2.5);
Journey leicester_nottingham = new Journey();
leicester_nottingham.setSingleCost(3.5);
System.out.println(leicester_loughborough.getSingleCost());
}
}

Related

How can I avoid having to rely on an object of another class to make the methods in a different class work?

Maybe the title was confusing, so here's a snippet of what I'm trying to avoid:
public class Generator{
private static GUI userInterface;
public static boolean specialValidator(String specialEntryText)
{
if(entryValidator(specialEntryText))
{
int specialChars = Integer.parseInt(specialEntryText);
int maxPossible = Integer.parseInt(userInterface.getLength())-3;
if(specialChars < 1 || specialChars > maxPossible)
{
return false;
}
return true;
}
return false;
}
public static void main(String[] args) {
userInterface = new GUI();
}
}
My program runs and functions as intended (keep in mind there is more to it than this), but I don't know if what I've done here is considered bad practice or what the downsides of doing it this way are. If my main method was not in the Generator class, this would not work, which seems like a problem to me.
Also, is there a specific name for what I did here, too?
The main method is the entry point of the program, and it needs to be in a class. It does not need to be in the Generator class.
As long as there is access to the class that you want to use, you can call it from another class. In you case it is public so it should be OK.
If it is in another class it could be something like
package yourPackage;
public class Main {
public static void main (String[] args) {
Generator gen = new Generator ();
//
gen.specialValidator(..);
}
}
Many things jump out at me.
There seems to be a dependency on GUI in specialValidator which is producing a "tight coupling" - you can't use the method without GUI.
This doesn't seem to make sense to me. You want to focus on reducing this coupling/dependency by passing all the required information into the method directly, for example...
public class Generator {
public static boolean specialValidator(String specialEntryText, int length) {
if (entryValidator(specialEntryText)) {
int specialChars = Integer.parseInt(specialEntryText);
// Any resason we're not using the specialEntryText length?
int maxPossible = length - 3;
if (specialChars < 1 || specialChars > maxPossible) {
return false;
}
return true;
}
return false;
}
}
Now specialValidator doesn't care "how" the information is generated, only that the information is made available to it. This "decouples" the method and makes it more independent, meaning you can call it any way you like (it also supports "dependence injection" making it more testable 😝)
And now you can call it anyway you like, for example...
public class Main {
public static void main(String[] args) {
Generator.specialValidator("some text", 8);
}
}

Accessing a particular instance of class inside the same class in java

I have a java code with the structure that is shown below:
public class x{
public static void main(string[] args)
{
ysample1 = new y(m)
ysample2 = new y(l)
....
}
}
public class y{
private int m_m
public y(int m)
{
m_m = m
}
public void control()
{
h h1 = new h(ysample2)
}
}
At some point when I want to call method control for ysample1 I may need to access ysample2 object.How can I define instance of class y global, so I can access ysample2 inside the control method in class y?
Does anyone know how can I fix this? Thanks.
You can't do what you want to do the way you wrote it.
I think you need to ridefine "control()" method like this:
public void control(Y ysample)
{
h h1 = new h(ysample)
}
So now you need to have an "ysample" as parameter and you can do from your main
control(ysample2);
and you will have what i understood from you question. If you need something else please comment.

How do I pass objects along from my Main class to other classes

I'm learning to code java and I encountered some problems in which I could use help understanding how things work.
I've made a list containing "Images", on my Main class, called "myList".
public class Main{
public static void main(String[] args) {
List<Images> myList = new ArrayList<Images>();
...
And I want to access it on this "System" class. But it doesn't seem to let me.
The plan is to access a position (the 3rd, in this example) on the given list (list.get(2)).
So I created the method "work".
//Example
public class System{
public static boolean work(List<Images> list){
if( list.get(2).equals(Something) )
return false;
else ... return true;
}
On this same System class I'm trying to use the method "work", giving it the List that I created on my Main class (myList).
public class System{
...
if( work(myList) ) //Don't know how to reffer to myList
return something;
Gives me the error "myList cannot be resolved to a variable".
So the problem is how to reffer to the list I made on my Main, named "myList".
Not sure if I explained that too well but any suggestions?
Make a List a property of System class, then pass it in the constructor
public class System {
private List<Images> images;
public System(List<Images> images) {
this.images = images;
}
//your other methods
}
Ah, in your main you should also pass the list:
System system = new System(myList);
Another option its to make myList public static and access it like this:
Main.myList
Declare one helper class and declare your list with setter and getters. Mainatin a singleton object of this class and use that list then in different other classes.
you need to make sure its accessible.
Right now your list is scoped the main() function. which is static to boot.
You need to make it accessible. You can do this by storing it in a static variable and having a static function return it.
Or you pass the main object along to other object, so they can access it.
public class Main {
private List<Images> myList = new ArrayList<Images>();
public static void main(String[] args) {
new Main(args);
}
public Main(String[] args) {
myList.add('foo.png');
myList.add('bar.png');
System mySystem = new System(this);
}
public List<Images> getImages() {
return myList();
}
}
public class System{
Main global;
public System(Main main) {
global = main;
}
public void doSomething() {
Iterator<Images> it = global.getImages().iterator();
while(it.hasNext()) {
Images images = it.next();
}
}
}

Making a static duplicate of non-static integer

For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.

compiling in bluej?

class box {
double ht,wdt,len;
box(double h,double w,double l) {
ht=h;
wdt=w;
len=l;
}
double volume() {
return ht*wdt*len;
}
}
class boxme {
public static void main(String args[]) {
box mybox= new box(1,2,3);
System.out.print("The volume is "+mybox.volume());
}
}
// For this code to be run in bluej,i still need to give the arguments after the object creation (though I have already given them in my code).The same code works well in cmd but shows this difference when attempted in bluej.Please provide a reason and solution to bring out an equivalence between bluej and cmd?? //
When you have two different classes and you want to use the methods in the other class, you have to create an instance of that class.
Right-click on the second class and run the public static void main(String args[]) function.
And please note the name of the class must start with an upper case letter and the fields must be private scoped for security, Objects should be always in lower case.
public class Box {
private double ht,wdt,len;
public Box(double h,double w,double l) {
ht=h;
wdt=w;
len=l;
}
public double volume() {
return ht*wdt*len;
}
}
public class boxme {
public static void main(String args[]) {
Box mybox= new Box(1,2,3);
System.out.print("The volume is "+mybox.volume());
}
}
You don't need to create an object while running it in BlueJ explicitly, since you already have the main function defined.
Right click on the class and run the public static void main(String args[])
function.

Categories

Resources