I'm learning object-oriented programming and started learning about inheritance. The assignment my teacher gave me was to make a counter object with 6 "buttons": Increment, Decrement, Reset, AddMemory, ResetMemory, and Quit. It is fairly straight-forward what each button does.
The requirements are that I have to use the JOptionPane command, I have to make a Counter class with a counter attribute, increment, decrement, reset, and quit methods, I have to make a MemoryCounter class with a memory attribute, restMemory, and addMemory method. I also have to make a MemoryCounterConsoleMenu class which makes the input box from the JOptionPane command and executes the appropriate method. The final thing I have to do is make a MemoryCounterTest class that brings the MemoryCounterConsoleMenu and MemoryCounter classes together
So I did all that and here it is:
The first one is the Counter class
public class Counter
{
private int counter = 0;
public void increment()
{
setCounter(getCounter() + 1);
}
public void decrement()
{
setCounter(getCounter() - 1);
}
public void reset()
{
setCounter(0);
}
public void setCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return counter;
}
}
This is the MemoryCounter class
public class MemoryCounter extends Counter
{
private int memory = 0;
public void resetMem()
{
setMemory(0);
}
public void addMem()
{
setMemory(getCounter());
}
public void setMemory(int memory)
{
this.memory = memory;
}
public int getMemory()
{
return memory;
}
}
Next is the MemoryConsoleMenu
public class MemoryCounterConsoleMenu
{
static MemoryCounter memCounter = new MemoryCounter();
static Counter counter = new Counter();
public static int console()
{
System.out.println(memCounter.getMemory());
Object[] options = {"Reset Mem", "Add Mem", "Increment", "Decrement", "Reset", "Quit" };
int objectIndex = JOptionPane.showOptionDialog(null, "Counter = " + counter.getCounter() + "Memory = "
+ memCounter.getMemory(), "MemoryCounter",JOptionPane.PLAIN_MESSAGE,
JOptionPane.PLAIN_MESSAGE, null, options, options[5]);
return objectIndex;
}
public static int change(int objectIndex)
{
if(objectIndex == 0)
{
memCounter.resetMem();
return 1;
}
else if(objectIndex == 1)
{
memCounter.addMem();
return 2;
}
else if(objectIndex == 2)
{
counter.increment();
return 3;
}
else if(objectIndex == 3)
{
counter.decrement();
return 4;
}
else if(objectIndex == 4)
{
counter.reset();
return 5;
}
else
{
return 6;
}
}
}
Finally, there is the MemoryCounterTest
public class MemoryCounterTest
{
public static void main(String[] args)
{
MemoryCounterConsoleMenu memoryConsole = new MemoryCounterConsoleMenu();
for(int i = 0; i != 6;)
{
i = memoryConsole.change(memoryConsole.console());
}
}
}
Everything works properly except for the memory value. It stays at a constant zero. I've done some troubleshooting myself and found that the only problem in the code is in the "addMem()" method is the MemoryCounter class particularly the implementation of the "getCounter()" method. It will only return 0 for some reason.
After figuring this out I have made no ground on why the problem is occuring or how to fix it
It stays at 0 because they are two separate counters.
MemoryCounter class extends the Counter class, so you don't need a separate
static Counter counter = new Counter();
Just do everything via memCounter.
I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}
Stupid question about Java basics, but I cannot beat it for days already.
I have a class with initialized data. Randomizer is here.
public class AddContract {
private Data data = new Data();
class Data {
final String CONNUM = String.valueOf(randInt());
public int randInt() {
int min = 1;
int max = 7777;
return (int) (Math.random() * max + min);
}
}
And I have another class:
public class ContractsPage {
public ContractsPage FindContractByContractNumber() {
AddContract.Data buffer = new AddContract.Data();
this.contractNumberFilter.clear();
this.contractNumberFilter.sendKeys(buffer.CONNUM);
return this;
}
}
Pls don't judge how it looks now coz I was trying many variants how to make it work.
So, I want get the same instanse of randInt in class ContractsPage as it is in class AddContract. But Object through new generates "new" rng.
tl;dr:
With random I get var=5 in Class1, I want to adress the same var=5 in Class2.
do the random oprtaions in constructor of the class and keep it in an instance variable.
public class AddContract {
private Data data = new Data();
private String bufferCONNUMStr = String.valueOf(data.randInt());
public String bufferCONNUM() {
return bufferCONNUMStr;
}
}
public class AddContract {
private Data data = new Data();
public String bufferCONNUM() {
return data.CONNUM;
}
public String bufferPURCHNUM() {
return data.PURCHASENUM;
}
class Data {
final String CONNUM = String.valueOf(randInt());
final String PURCHASENUM = String.valueOf(randInt());
public final int randInt() {
int min = 1;
int max = 7777;
return (int) (Math.random() * max + min);
}
}
}
Can anyone tell me how to count the number of instances of a class?
Here's my code
public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
//getters and setters
public int getGear() {
return gear;
}
public void setGear(int Gear) {
this.gear = Gear;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int Speed){
this.speed = Speed;
}
public int getSeatHeight() {
return seatHeight;
}
public void setSeatHeight(int SeatHeight) {
this.seatHeight = SeatHeight;
}
public String getColor() {
return color;
}
public void setColor(String Color) {
this.color = Color;
}
}//end class
public class Variable extends Bicycle {
public Variable(int gear, int speed, int seatHeight, String color) {
super(gear, speed, seatHeight, color);
}
}//end class
public class Tester {
public static void main(String args[]){
Bicycle bicycle1 = new Bicycle(0, 0, 0, null);
bicycle1.setColor("red");
System.out.println("Color: "+bicycle1.getColor());
bicycle1.setSeatHeight(4);
System.out.println("Seat Height: "+bicycle1.getSeatHeight());
bicycle1.setSpeed(10);
System.out.println("Speed: "+bicycle1.getSpeed());
bicycle1.setGear(6);
System.out.println("Gear: "+bicycle1.getGear());
System.out.println("");//space
Bicycle bicycle2 = new Bicycle(0, 0, 0, null);
bicycle2.setColor("black");
System.out.println("Color: "+bicycle2.getColor());
bicycle2.setSeatHeight(6);
System.out.println("Seat Height: "+bicycle2.getSeatHeight());
bicycle2.setSpeed(12);
System.out.println("Speed: "+bicycle2.getSpeed());
bicycle2.setGear(6);
System.out.println("Gear: "+bicycle2.getGear());
System.out.println("");//space
}//end method
}//end class
The class variable is to be used to keep count of the number of instances of the Bicycle class created and the tester class creates a number of instances of the Bicycle class and demonstrates the workings of the Bicycle class and the class variable. I've looked all over the internet and I can't seem to find anything, could someone show me how to do it please, thanks in advance :)
Since static variables are initialized only once, and they're shared between all instances, you can:
class MyClass {
private static int counter;
public MyClass() {
//...
counter++;
}
public static int getNumOfInstances() {
return counter;
}
}
and to access the static field counter you can use MyClass.getNumOfInstances()
Read more about static fields in the JLS - 8.3.1.1. static Fields:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (ยง12.4).
Note that counter is implicitly set to zero
Pleae try the tool of java
jmap -histo <PDID>
Out put
num #instances #bytes class name
----------------------------------------------
1: 1105141 97252408 java.lang.reflect.Method
2: 3603562 86485488 java.lang.Double
3: 1191098 28586352 java.lang.String
4: 191694 27035744 [C
In addition, you should override finalize method to decrement the counter
public class Bicycle {
...
public static int instances = 0;
{
++instances; //separate counting from constructor
}
...
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
#Override
protected void finalize() {
super.finalize();
--instances;
}
}
You should have in mind that static variables are CLASS scoped (there is no one for each instance, only one per class)
Then, you could demonstrate instance decrement with:
...
System.out.println("Count:" + Bicycle.getNumOfInstances()); // 2
bicycle1 = null;
bicycle2 = null;
System.gc(); // not guaranteed to collect but it will in this case
Thread.sleep(2000); // you expect to check again after some time
System.out.println("Count again:" + Bicycle.getNumOfInstances()); // 0
why not using a static counter?
public class Bicycle {
private static int instanceCounter = 0;
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
instanceCounter++;
}
public int countInstances(){
return instanceCounter;
}
........
You just need static counter in class.
public class Bicycle {
private static volatile int instanceCounter;
public Bicycle() {
instanceConter++;
}
public static int getNumOfInstances() {
return instanceCounter;
}
protected void finalize() {
instanceCounter--;
}
}
As mentioned in many comments finalize() is not recommended to use so there could be another approach to count the Bicycle instances -
public class Bicycle {
private static final List<PhantomReference<Bicycle>> phantomReferences = new LinkedList<PhantomReference<Bicycle>>();
private static final ReferenceQueue<Bicycle> referenceQueue = new ReferenceQueue<Bicycle>();
private static final Object lock = new Object();
private static volatile int counter;
private static final Runnable referenceCleaner = new Runnable() {
public void run() {
while (true) {
try {
cleanReferences();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
static {
Thread t = new Thread(referenceCleaner);
t.setDaemon(true);
t.start();
}
private Bicycle() {
}
public static Bicycle getNewBicycle() {
Bicycle bicycle = new Bicycle();
counter++;
synchronized (lock) {
phantomReferences.add(new PhantomReference<Bicycle>(new Bicycle(), referenceQueue));
}
System.out.println("Bicycle added to heap, count: " + counter);
return bicycle;
}
private static void cleanReferences() {
try {
PhantomReference reference = (PhantomReference) referenceQueue.remove();
counter--;
synchronized (lock) {
phantomReferences.remove(reference);
}
System.out.println("Bicycle removed from heap, count: " + counter);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getNumOfBicycles() {
return counter;
}
}
public class BicycleTest {
public static void main(String[] args) {
int i = 0;
while (i++ < 1000) {
Bicycle.getNewBicycle();
}
while (Bicycle.getNumOfBicycles() > 0) {
try {
Thread.sleep(1000);
System.gc(); // just a request
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Alternatively, you can create a counter with an initializer block and a static variable.
class SomeClass
{
private static int instanceCounter;
{
instanceCounter++;
}
}
Initializer blocks get copied by the compiler into every constructor, so, you will have to write it once no matter how many constructors you will need (As referred into the above link). The block in {} runs every time you create a new object of the class and increases the variable counter by one.
And of course get the counter by something like:
public static int getInstanceCounter()
{
return instanceCounter;
}
or directly
int numOfInstances = SomeClass.instanceCounter;
If you do not make numOfInstances private
One basic approach is to declare a static numeric member field thats incremented each time the constructor is invoked.
public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
public static int bicycleCount = 0;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
bicycleCount++;
}
...
}
If you want to count and test instances based on the number of objects created, you can use a loop to see what really is happening. Create a constructor and use a static counter
public class CountInstances {
public static int count;
public CountInstances() {
count++;
}
public int getInstaces() {
return count;
}
public static void main(String []args) {
for(int i= 0; i<10; i++) {
new CountInstances();
}
System.out.println(CountInstances.count);
}
}
public class Number_Objects {
static int count=0;
Number_Objects(){
count++;
}
public static void main(String[] args) {
Number_Objects ob1=new Number_Objects();
Number_Objects ob2=new Number_Objects();
Number_Objects obj3=new Number_Objects();
System.out.print("Number of objects created :"+count);
}
}
So I made a die class that is supposed to create die, and then allow me to roll them, pull their values and number of sides. My problem now is that I cannot roll the die during testing as it throws a NullPointerException.
Here's the die class code:
package com.catalyse.die;
import java.util.Random;
public class Die
{
// instance variables
private static int dieNum = 0;
private int myDieValue;
private int myDieSides;
private Random rand;
// Dice Class Constructors
public Die()
{
dieNum++;
this.myDieValue = 1;
this.myDieSides = 4;
}
public Die(int numSides)
{
if ((numSides < 4) || (numSides > 100)) {
System.out.println("Error! You cannot have more than 100 sides or less than four!");
System.exit(0);
}
else {
myDieSides = numSides;
myDieValue = 1;
}
}
// getter methods
public int getDieSides()
{
System.out.println(myDieSides);
return 0;
}
public int getDieValue()
{
System.out.println(myDieValue);
return 0;
}
// setter methods
private void setDieSides(int newNumSides)
{
myDieSides = newNumSides;
}
public void rollDie()
{
myDieValue = (rand.nextInt(myDieSides) + 1);
}
// other methods
public void printDie(int dieNum)
{
if (dieNum == 1) {
System.out.println("Die Value: "+myDieValue);
}
else {
System.out.println("Die "+dieNum+" Value: "+myDieValue);
}
}
}
Here is the testing class.
package com.catalyse.die;
public class TestDieClass
{
public static void main(String [] args)
{
Die One = new Die();
Die Two = new Die(50);
Die Three = new Die(99);
One.getDieSides();
One.getDieValue();
Two.getDieSides();
Two.getDieValue();
Three.getDieSides();
Three.getDieValue();
One.rollDie();
Two.rollDie();
Three.rollDie();
One.getDieValue();
Two.getDieValue();
Three.getDieValue();
}
}
Here is the error
4
1
50
1
99
1
Exception in thread "main" java.lang.NullPointerException
at com.catalyse.die.Die.rollDie(Die.java:83)
at com.catalyse.die.TestDieClass.main(TestDieClass.java:27)
myDieValue = (rand.nextInt(myDieSides) + 1);
You haven't initialized rand so rand is null
So,
private Random rand= new Random();