how do I change instanced class variables - java

my code simplified looks something like:
//class 1
public class Main
{
public static void main(String[] args)
{
Process process = new Process(0); //creates new process with ID of 0
process.id = 1; //error - I can't call and change process.id here
System.out.println(process.id);
}
}
//class 2:
public class Process()
{
//constructor
public Process(int tempID)
{
int id = tempID;
}
}
Where I have the comment error is what I'm stuck with. I want to access and change the id variable of this instanced class I have, but I'm not sure how to

Defined id as an instance variable.
Since id is defined inside the method locally that is why you can access it using p.id.
So create id as an instance variable like and for updating its value create a setter method. So your class would look like this.
public class Process(){
public int id; //<- Instance Varaible
//constructor
public Process(int tempID){
int id = tempID;
}
//Setter method
public void setId(int id){
int id = tempID;**strong text**
}
}
Now you can change the value like this
Process p = new Process(0);
p.setId(1); // Change Value
System.out.println(p.id);

Related

How to construct several objects in one class, then read in another class

I apologize if this is a basic question.
I am attempting to create several unique objects in one class, then get the values of one of the objects in another class.
I have created two classes and followed some examples to end with this
public class Type {
public String name;
public int healthmod;
public int strmod;
public int accmod;
public int armmod;
public int refmod;
public int intmod;
public String advantages;
public String disadvantages;
public Type() {
Type fire = new Type();
fire.name = "Fire";
fire.healthmod = 0;
fire.strmod = 1;
fire.accmod = 0;
fire.armmod = 0;
fire.refmod = 0;
fire.intmod = 1;
}
}
and then in the main class:
Player.typename = Type.fire.name;
Edit
public class Player {
public static String name, classname, racename, elementname;
public static int maxhealth, healthpts, healthptscost, healthupgnum, healthmod, currenthealth, basehealth;
public static int str, strpts, strptscost, strupgnum, strmod;
public static int acc, accpts, accptscost, accupgnum, accmod;
public static int arm, armpts, armptscost, armupgnum, armmod;
public static int ref, refpts, refptscost, refupgnum, refmod;
public static int intelligence, intpts, intptscost, intupgnum, intmod;
public static int mana, maxmana, managain, managainak;
public static int hitChance, critChance, Level, statPts, statTotal, damage, damageDealt, goldmult, itemmod, itemdefboost, itemdamboost, itemmodboost;
public static String[] focusStats;
}
What I am trying to do is create a few objects in the Type class and access them in the Main class in order to store the values in the Player class, but in the Main class, fire "cannot be resolved or is not a field"
Edited to provide more clarity on the purpose.
You are completely mixing things here.
In the concstructor of Type you are creating a new local Object named fire. This object is only available in this constructor and not outside of it, e.g. in the main class.
A valid solution can only be found if you give more information about what you try to accomplish.
I could write like that your Type construct:
public Type() {
this.name = "Fire";
this.healthmod = 0;
this.strmod = 1;
this.accmod = 0;
this.armmod = 0;
this.refmod = 0;
this.intmod = 1;
}
So when using the Player class in your Main method, like that:
public static void main(String args[]) {
Type type = new Type();
Player.typename = type.name;
}
You can also put a reference of type inside Player class like that:
public class Player {
public static Type fire;
}
So in your main method like that:
public static void main(String args[]) {
Player.fire = new Type();
System.out.println(Player.fire.name);
}

Getting Variables From Java constructor

I'm new to Java programming, sorry if this is a dumb question.
I find it hard to word this question properly, but I have an assignment to create a aircraft class that can make aircraft land, takeoff etc. And need to test it using Testclass. When the new object are entered it automatically assigns a unique ID to the aircraft in the constructor.
I can do this using a instance method fine as it has a return value which is returned to to Testclass. The question wants me to do this in the constructor itself, however, the constructor never returns anything. So the variable never gets sent to the Testclass. I clearly am not understanding OOP properly. Even when I try to just use a getter method to get the ID created in the constructor it gives me the initialized variable before the the constructor has worked on this. This is the code I have so far and its completely wrong I know but if someone could point me in the right direction or tell me how to word this question better it would be a massive help.
// I need to enter 3 aircraft into the system in the testclass
public class Aircraft {
private int aircraftID;
private static int lastID;
private String airportcode;
private int ID = 100;
private int count;
public Aircraft(int a, int b, int c){
// Constructor
// Assign ID
this.ID = a;
lastID = ID;
ID++;
this.ID =b;
lastID = ID;
ID++;
}
}
OK, you want to create an Aircraft that has an automatically-assigned unique identifier, and can take off and land. That implies you need a field for tracking the identifier, a field for tracking whether it's in the air (or not), and methods for the take off and land operations. You also need a static field for generating the unique identifiers. (Note that this implementation isn't thread safe.)
private class Aircraft {
private static int staticId = 0;
private int uniqueId = 0;
private boolean onGround = true; // Aircraft start on the ground in this implementation
public Aircraft(){
this.uniqueId = staticId; // putting this line first makes uniqueId zero-indexed in effect
staticId++;
}
public void land(){
onGround = true;
}
public void takeoff(){
onGround = false;
}
public boolean isFlying(){
return !onGround; // If it's not on the ground, it's flying
}
public int getUniqueId(){
return uniqueId;
}
}
Unit tests checks all of the methods and expected functionality of the class in question:
import org.junit.Test;
import static org.junit.Assert.*;
import Aircraft;
class Testclass {
private final Aircraft aircraft = new Aircraft();
#Test
public void hasId(){
aircraft.getUniqueId() >= 0;
}
#Test
public void canLand(){
assertTrue(aircraft.land());
}
#Test
public void canTakeOff(){
assertTrue(aircraft.takeOff());
}
#Test
public void checkFlightOperationsAreTrackedCorrectly(){
aircraft.land();
assertFalse(aircraft.isFlying());
aircraft.takeOff();
assertTrue(aircraft.isFlying());
}
}
As pointed out a constructor does not return anything (the simplified version is that with new it returns an object instance). I am kinda guessing at what you are trying to acomplish, but I'll have a go anyways. It seems to me that you are trying to cram the construction of 3 objects into one constructor - which is why your constructor has 3 parameters. Also you are playing havoc with the IDs.
I have removed all the variables that I didnt quite understand, leaving only ID that increments with each instantiated Aircraft. The #Override is mainly just for show.
public class Aircraft {
private int aircraftID;
private static int lastID = 0;
#Override
public String toString(){
return "Aircraft_" + this.aircraftID;
}
public Aircraft() {
lastID++;
this.aircraftID = lastID;
}
}
I took the liberty and wrote the TestClass just to see if we have the same thing in mind. Again the printAircraft() method is for show.
public class TestClass {
private List<Aircraft> aircrafts;
public TestClass(){
aircrafts = new ArrayList<>();
}
public void addAircraft(Aircraft a){
aircrafts.add(a);
}
public void printAircraft(){
Iterator<Aircraft> it = aircrafts.iterator();
while(it.hasNext()){
System.out.println(it.next().toString());
}
}
}
and to test it, we create and instance of TestClass add 3 Aircraft instances and print out the contents
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.printAircraft();
}
This would be the case if you are to write the TestClass. If that is given, it would help to know what it looks like - maybe that would help us understand better.

Instantiate array of objects with a variable

I wrote some classes in Java but when I run the program I receive the error "ArrayIndexOutOfBoundsException", the incriminate class is this:
public class Bank {
private String name;
private int maxbankaccount;
private int activebankaccount;
private String radice = "IT8634";
private Conto[] bankaccount = new Conto[maxbankaccount];
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
}
}
I wrote a tester class to test :
public class TestBank {
public static void main (String[] args) {
Bank b1 = new Bank("Fidelity", 10);
b1.addconto("PROVA");
}
}
Since I didn't seem to have made logical errors using the array I debugged, I realized that in the creation of the array of objects the maxbankaccount variable isn't 10 (value passed in Test) but as default value (0),then I tried passing 10 directly and it works good. Why is not the value 10 of maxbankaccount passed but 0?
private Conto[] bankaccount = new Conto[maxbankaccount];
This initialization takes place before the rest of the constructor runs.
Move it into the constructor:
public Bank(String name, int maxbankaccount) {
this.name = name;
this.maxbankaccount = maxbankaccount;
this.bankaccount = new Conto[maxbankaccount];
}
You have indeed made a logical error. The array bankaccount is getting initialized when the class is instantiated and is always 0.
Move it into the constructor and initialize it.
public Bank(String name, int maxbankaccount) {
/* ... */
this.bankaccount = new Conto[maxbankaccount];
}
Further more than the issues that are in the other answers, this
private int activebankaccount;
does not initialize the variable activebankaccount
So in:
public void addconto(String cf) {
bankaccount[activebankaccount] = new Conto(radice + activebankaccount , cf);
activebankaccount++;
}
you are using an uninitialized vale as index of the array bankaccount

What happens when a call made to an constructor (clear concept in this context)?

I think that java will not initialize the a with four values. But I'm wrong, can you please explain me how it does this? I mean what it does when a constructor called because I'm not initialize a in constructor.
class A {
int[] a = {1,2,3,4};
A() {
a[0] = 3;
}
}
class ClassTest1 {
public static void main(String args[]) {
A b = new A();
System.out.println("hey " + b.a[0] );
System.out.println("hey " + b.a[1] );
}
}
If you explain in detail and with some external resource to understand internals, it could be better for a newbie(me).
When you have int[] a = {1,2,3,4} it compiles that line into the top of your constructor. So your constructor really looks like this:
a = {1,2,3,4};
a[0] = 3;
Now, that's a very simplistic definition of what happens. If you had multiple constructors, you could view it as putting it in all of them, but you could also view it as putting it in only one of them (the one you actually called...).
Consider this:
class Counter {
static int nextId = 0;
static int nextId() { return nextId++; }
final int id = nextId();
final String name;
public Counter() {
this("Unnamed counter");
}
public Counter(String name) {
this.name = name;
}
}
So you have the option to create a counter without a name, and you get just a default name. Now from the example above, you could extrapolate that your constructors magically turn into the following:
public Counter() {
this.id = nextId();
this("Unnamed counter");
}
public Counter(String name) {
this.id = nextId();
this.name = name;
}
But we know this isn't okay - it attempts to set id in the generic constructor, but then goes into the named constructor and tries to set it again. You can't set a final variable once it's been set!
So instead, we can think of it like this: whatever constructor we actually called gets the extra initialization lines, but the ones that might get chained don't get the extra lines.

java - an enum question

I have encountered a weird problem in my app (java).
I have an enum. Something like that
public enum myEnum implement myIntrface{
valueA(1),valueb(2),valuec(3),valued(4)
private int i;
// and then - a constructor
public MyEnum(int number){
i = number;
}
private MyObj obj = new MyObj;
// getter and setter for obj
}
and in another class I have this
MyEnum.valueA.setObj(new Obj(...))
in briefe - I have an enum with a private instance member that has a set and a get.
So far so good -
The only thing that amazes me is that later on I look at the value of the MyEnum.valueA().obj is null.
there is nothing that updates the value to null, I have even gave it a default value in the constructor and I still see it null later.
any suggestions?
Enums should be un-modifiable classes so you shouldn't really be doing this. If your looking to modify the state of a type based object like an enum you should use an final class approach with embedded constants. Below is an example of a class based approach with a modifiable name an a un-modifiable name...
public final class Connection {
public static final Connection EMAIL = new Connection("email");
public static final Connection PHONE = new Connection("phone");
public static final Connection FAX = new Connection("fax");
/**/
private final String unmodifiableName; //<-- it's final
private String modifiableName;
/*
* The constructor is private so no new connections can be created outside.
*/
private Connection(String name) {
this.unmodifiableName = name;
}
public String getUnmodifiableName() {
return unmodifiableName;
}
public String getModifiableName() {
return modifiableName;
}
public void setModifiableName(String modifiableName) {
this.modifiableName = modifiableName;
}
}
The purpose of enums is to represent constant values. It does not make any sense to set the fields of a constant value.
You should declare your fields as final, and use the constructor to initialize all of them.
For reference, the following code works as expected:
public class Test {
public static enum MyEnum {
valueA(1),valueb(2),valuec(3),valued(4);
private int i;
private Object o;
private MyEnum(int number) {
i = number;
}
public void set(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
public static void main(String[] args) {
System.out.println(MyEnum.valueA.get()); // prints "null"
MyEnum.valueA.set(new Integer(42));
System.out.println(MyEnum.valueA.get()); // prints "42"
}
}
the cause of this problem is the db40 framework . It loads an enum from the db using reflection. This is well documented .
http://developer.db4o.com/Forums/tabid/98/aft/5439/Default.aspx

Categories