How to set variable within Java class from within another class - java

I'm trying to set up a simple set of classes in Java in such a way that a specific Trader class (see below) can 'talk' to other Robot class objects, as identified by a customer id, and set an offer variable within it.
My intial attempt fails because I've defined customer as a String, which is why customer.receiveTender(target) won't work. But I also tried Agent and the Customer subclass but they don't work.
I'm very new to Java - can someone point me in the right direction?
public class Trader extends Robot {
private String target;
public String selectTarget(String target) {
target = target;
}
public void issueOffer(String target, String customer) {
customer.receiveOffer(target);
}
}
UPDATE:
public class Robot {
private String id;
public Robot() {
id = "No name yet";
}
public void setID (String newID) {
id = newID;
}
public String getID() {
return id;
}
}
public class Customer extends Robot {
private String target;
public void receiveOffer(String target) {
target = target;
}
}

Because, receiveTender() is not a member of String class.
Below line of code means an object with name customer, which is String type has method receiveTender and takes argument as String i.e. target. But, if you look at the String class, it doesn't have any method with name receiveTender and that's the reason. It won't compile.
customer.receiveTender(target);
As per your updated code, receiveOffer is a member of Customer class, which means you need to have instance of Customer class to access its method and that means it should be
public void issueOffer(String target, Customer customer) {
customer.receiveOffer(target);
}

Majority of the times, one class can speak to another class only when the class has an object of another class. Inheritance come into picture for "is a" relationship. The Trader class written above will only make sense if Trader is a Robot otherwise create two separate classes as Robot and Trader.

Related

Find object created inside a method in other class

For example, 2 class: Ticket and Customer
public class Ticket{
private String cstName;
public Ticket(String name){
this.cstName = name;
}
}
public class Customer{
private String name;
public void book(){
Ticket t = new Ticket(t);
}
}
How can I find and use t object elsewhere ???
What you ask for is completely impossible. An object is made, the object is assigned to a local variable, and the method ends.
As the method ends, all local variables (and t is a local variable), immediately go into the bin and there is nothing in java that lets you 'plug into' this process or that lets you stop this process. The variable is just gone.
The object is still on the heap somewhere, but no longer accessible. Eventually it will be garbage collected. There's nothing you can do about that, either. Java does not have a 'list all objects in the heap' method and never will.
You can mess with reference queues which is an extremely advanced topic that in no way is suitable given the way this question is stated, and wouldn't work for arbitrary methods like this.
If you control the code of Ticket itself you can save the reference as part of the constructor, which would be extremely bad design, and would have nothing at all to do with the notion of t, or that the book method made it.
What you presumably want, is a field:
public class Customer {
private String name;
private Ticket ticket;
public void book() {
this.ticket = new Ticket(t);
}
public Ticket getTicket() {
return this.ticket;
}
}
and now you could do:
Customer c = new Customer();
c.book();
Ticket t = c.getTicket();
or perhaps do:
public class Customer {
private String name;
private Ticket ticket;
public Ticket book() {
this.ticket = new Ticket(t);
return this.ticket;
}
}
and now you could do:
Customer c = new Customer();
Ticket t = c.book();

How do I create some objects to store in an arrayList, which is a attribute of sub class, from a parent class in Java?

So I have 3 classes, Lair, LairLocation & Minion. I created an ArrayList, which is supposed to store Minion objects, and this is an attribute of LairLocation. I'm supposed to create some objects to store in ArrayList, from the parent class Lair. Both LairLocation and Minion and sub-classes of Lair.
Whenever I try to create objects to store in ArrayList form my parent, I keep getting an error saying 'minion cannot be resolved' and telling me to create a local variable etc. Please help
LairLocation
'''
public class LairLocations extends Lair
{
public static ArrayList<Minion> minions = new ArrayList<Minion>();
}
'''
Lair
'''
public class Lair
{
public void createMinions()
{
minions.add("12", "Mine", "Me");//This is giving me the error
}
}
'''
Minion
'''
public class Minion extends Lair
{
private String id;
private String fName;
private String lName;
public Minion(String Id, String fName, String lName)
{
this.id = id;
this.fName = fName;
this.lName = lName;
}
}
'''
You're trying to access a field of a subclass from its parent class. This does not work this way.
You can only access fields of a parent class (if they're public or protected).
So, you either have to move your minions field to the parent class Lair (and make it non-static, by the way), or access this object via LairLocation class: LairLocation.minions() (if the field is supposed to be static).
Also, this line of code is incorrect: minions.add("12", "Mine", "Me");
The add() method accepts only one element.
It should probably be: minions.add(new Minion("12", "Mine", "Me"));
You have to call new Minion() to get a new minion.
minions.add( new Minion( "12", "Mine", "Me") );

deleting an object in Bluej

I'm making an project according to the movie The Ghost and The Darkness, I have created an object of human class and 2 objects of lion class by GUI.
public class Lion{
private String Name;
public Lion(String Name){
this.Name=Name;
}
}
this is Human class,
public class Human{
private String name;
public Human(String name){
name="Hunter";
}
}
Now, I want to make an object of hunt that will kill/delete the objects of Lion.
I assume you want to create something similar to a game where characters can be killed (or removed from game).
There are at least 2 ways you can go about doing it:
//You can plan the hierarchy for your classes first..
//This is optional, but to make it interesting, we create a super class
abstract class LivingThings
{
private Boolean isAlive;
private String name;
public LivingThings(String name){
this.name = name;
isAlive = true; //When an object is created, set it to alive
}
public void setAlive(Boolean flag){
this.isAlive = flag;
}
}
1. Flagging it as dead
Now you Human and Lion can be a subclass of LivingThings and all sub-classes will posses a property known as isAlive:
class Lion extends LivingThings{
//Your other properties for Lion
}
class Human extends LivingThings{
//Your other properties for Human
public void kill(LivingThings target){
target.setAlive(false); //Kill an object (but object still exist in game)
}
}
If you are making a game, very often you do not need to remove the object from the game immediately Is was killed. But instead, we flag is as "dead".
2. Deference the object (not recommended)
If you really want to remove it. You can do it as such:
public void kill(LivingThings target){
target = null; //Remove object (Wait for Garbage Collector to collect it)
}
However, by setting it to null may cause undesirable consequences as other parts of your program may still be referencing to that object, hence giving you NullPointerException.

Why do these two apparently identical objects have different class types? [duplicate]

This question already has answers here:
What is Double Brace initialization in Java?
(13 answers)
Closed 7 years ago.
I have a class User, only have two fields: id, name
package test;
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then in the Main class, I tried to initialize the User object with two different approach:
package test;
/**
* #author lhuang
*/
public class Main {
public static void main(String[] args) {
User u = new User() {
{
setId(1l);
setName("LHuang");
}
};
System.out.println(u.getClass());
User u2 = new User();
u2.setId(1l);
u2.setName("LHuang");
System.out.println(u2.getClass());
}
}
then I can get the output
class test.Main$1
class test.User
The interesting is why the u class is the inner class type of Main? But actually I still can use the u.getId() and u.getName() method.
You're creating an anonymous class that extends from User here:
User u = new User() { //<-- this open bracket defines a new class
{
setId(1l);
setName("LHuang");
}
};
This
User u = new User() { // here's your derived class
{ // here's the initialiser block
setId(1l);
setName("LHuang");
}
};
creates a new anonymous subclass of User (the outer set of braces), and then defines an initialiser block within that (the inner set of braces).
It's often advised to avoid the above construction for reasons of clarity (not many people are aware of how it works), and since you're creating an inner class, it'll have an implicit reference to the outer class. This can cause issues for garbage collection and serialisation.
Having said that, I would use the above sparingly (e.g. for setting up test collections in unit tests etc. due to its conciseness)

Java cannot get one class inherit from another

Ok, I have 2 classes that need to inherit from another class..
When I move id fields over it says that it cannot access that fields as it is private. so I call the public get method... but it still doesnt work. What I need to do is move all field into vehicle and make taxi + shuttle to inherit from it
public class Vehicle
{
// A unique ID
private String id;
// The destination
private String destination;
// The location of this taxi.
private String location;
/**
*Constructor for vehicle
*/
public Vehicle(String id)
{
this.id=id;
}
Change the Vehicle's constructor so that it takes an int argument, which you then assign to the classes id field
public Vehicle(int id) {
this.id = id;
}
Now, you'll be required to call super(int ) in of your child classes, which will set the id field
public Taxi(String base, String id){
super(id);
//...
}
ps- I have no idea what this is trying to do, but it doesn't do anything...
public void ID(){
Vehicle id= new Vehicle();
id.getID();
}
And given the fact that we've changed the constructor, it will no lager compile...
public class Vehicle
{
// A unique ID
private String id;
// The destination
private String destination;
// The location of this taxi.
private String location;
/**
*Constructor for vehicle
*/
public Vehicle(String id)
{
this(id, null);
}
/**
*Constructor for vehicle
*/
public Vehicle(String id, String location)
{
this.id = id;
this.location = location;
}
/**
* Returns ID.
*
*/
public String getID()
{
return id;
}
public String getDesitnation() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getLocation() {
this.location = location;
}
public void setLocation(String location) {
this.location = location;
}
}
public class Taxi extends Vehicle
// Whether it is free or not.
private boolean free;
/**
* Constructor for objects of class Taxi.
* #param base The name of the company's base.
* #param id This taxi's unique id.
*/
public Taxi(String base, String id)
{
super(id, base);
free = true;
}
}
public class Shuttle extends Vehicle
{
// The circular route of this shuttle.
private ArrayList<String> route;
// The destination number in route that the shuttle is
// currently headed for.
private int destinationNumber;
/**
* Constructor for objects of class Shuttle
* #param id This shuttle's unique id.
* #param route The route taken by this shuttle.
* The first entry is the starting location.
*/
public Shuttle(String id, ArrayList<String> route)
{
super(id);
this.route = route;
}
}
The attributes declared as private can not be accessed from a subclass. Either declare them as protected or create a constructor in the superclass that assigns them, and call that constructor from the subclass' constructor using super().
When i move id fields over it says that it cannot access that fields as it is private.
This word already tells you what restrict from inheritance.
In Java, every class can have totally private data in it, the key word private symbol the data that only this class can have, even you extends from it, those inherited class still can not use private field.
To utilize inheritance advances in Java but still do not want be accessed by class out of your package, you need to make it protect rather than private scope, hence those member fields would be inherited from base class.
You have more than one problem here, here's what I can see as an issue with your code:
1) I'm assuming that both your code for Vehicle and Taxi are in separate class files. Multiple classes in one file can happen but is a bad practice.
2) id is not accessible for two reasons. The first is because you did not call super(). When extending a class, the first thing you have to do is call the super() class to grab all of the parent's variables. The second is because you've given it private access. Private means it is visible only to the Vehicle class. You can fix this two ways. The first is to change the visibility to something other than private. The second is to create getter and setter methods inside the Vehicle class that allow you to change id from other classes when using the setter.
3) The lines:
location = base; destination = null; free = true;
What is location? What are base, destination, and free? These will also cause errors, you need to declare these variables first as instance variables before your constructor.
Hope this helps!

Categories

Resources