How to get value of variable from other class? - java

I have a public integer variable (MainReg) in my Counter Class. I want to get value of this variable and set it in my JComponent class. Here is piece of my JComponent class:
public class Komponent2 extends JComponent implements ActionListener
{
Counter counter3;
.
.
.
int a = counter3.valueOf(MainReg);
But it doesn't work. I tried also:
int a = valueOf(counter3.MainReg);
int a = counter3.valueOf(counter3.MainReg);
int a = counter3.MainReg;
But it still doesn't work. How can I get this variable? Thanks for helping me.
EDIT
Here is my Counter class:
import java.util.Observable ;
public class Counter extends Observable
{
public int MainReg;
public int CompareReg;
public Mode countMode;
public boolean OVF;
private int a=0;
public Counter()
{
OVF=false;
}
public void setCompareReg(int dana)
{
CompareReg=dana;
}
public void setMainReg(int dana2)
{
MainReg=dana2;
}
public void setMode(Mode countMode)
{
this.countMode=countMode;
}
public void Count()
{
if (countMode==Mode.UP)
{
MainReg++;
OVF=false;
if (CompareReg < MainReg)
{
OVF=true;
MainReg=0;
setChanged();
notifyObservers();
}
}
else if (countMode==Mode.UPDOWN)
{
if(MainReg >= CompareReg)
{
a=MainReg;
MainReg--;
OVF=true;
}
else
{
if(MainReg >= a)
{
MainReg++;
OVF=false;
}
else
{
MainReg--;
if(MainReg==0)
{
a=0;
}
OVF=false;
}
}
}
else if (countMode==Mode.CONTINOUS)
{
MainReg++;
OVF=false;
if (65536 < MainReg)
{
MainReg=0;
OVF=true;
}
}
}
}

Well I see two ways you can do this.
Your MainReg integer is public, you could simply use int i = counter3.MainReg;
Or you could create a getMainReg() method in your Counter class. Then call it from whatever class.
EX:
public int getMainReg() {
return this.MainReg;
}

Give your Counter class getter methods, and then call them when you need to access their values. i.e.,
public int getMainReg() {
return mainReg;
}
public int getCompareReg(){
return compareReg;
}
public Mode getCountMode() {
return countMode;
}
And make your fields all private. Also your code should obey Java naming rules: variable names should begin with lower-case letters.
Also be sure that you've initialized your counter variable in the class that uses it, either by creating a new instance, or if appropriate, passing in a valid instance in a constructor or method parameter.

Related

How can i call the method from another class?

Hi i am trying to solve the problem I am facing
public class exam {
public static void main(String[] args) {
test1 a = new test1();
}
int zahl(int x, int y) {
int e;
if(x>y) {
e=x-y;
}else {
e=y-x;
}
if(e==0) {
return 0;
}
int z=0;
int i=1;
while(i<=e) {
z=z+i;
i++;
}
return z;
}
}
what I want to do is to call the zahl method to the test1 class
public class test1{
private exam b;
public void init() {
b = new exam();
}
void test() {
int result = b.zahl(2, 2);
assertEquals(1, result);
}
}
this is what I have tried, but it returns nothing, even though it's supposed to show me error.
You should probably be declaring your functions with the public tag i.e. public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.
For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.

Inheritance var java

this is the qa:
Define a class called MoreSpeed which extends the following class, and which provides a new method called incSpeed() which adds 1 to the inherited variable length.
this is my answer:
public class Speed {
private int length = 0;
public int getSpeed () { return length; }
public void setSpeed (int i) {
if (i > 0) {
length = i;
}
}
}
public class MoreSpeed extends Speed {
private int length;
public int incSpeed() {
return length+1;
}}
its says that the syntax is good but the class operation is wrong.
please help me,thanks.
No. You are shadowing the length from Speed. Instead, implement incSpeed with getSpeed() like
public int incSpeed() {
return getSpeed() + 1;
}
If you are supposed to modify it as well then use setSpeed(int) to do so
public int incSpeed() {
int s = getSpeed() + 1;
setSpeed(s);
return s;
}

Is it possible to avoid duplicate code when implementing methods for two similar class?

I have two classes: Fish and Plant. They do not inherit from any classes.
But both of them have one method called isAlive() which have the same implementation details. Now I have a list of fish and another list of dog and I need to remove dead fish and dead dog. I want my method to have same name but it is not possible without adding additional field to method signature. Is it possible I do not need to write additional chunk of code which does the same as the last chunk of code?
Below is the code. For class Model, Fish and Plant are two data members and they are ArrayList of Fish and Plant objects.
Is there any way I can write only one method called count and I do not need to add additional field to my method signature or modify my return type?
public class Fish{
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Plant{
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Model{
private int countDeadFish() {
int totalCount = 0;
for(Fish aFish : this.fish) {
if(aFish.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
private int countDeadPlants() {
int totalCount = 0;
for(Plant plant : this.plants) {
if(plant.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
}
If you do not want to use inheritance, then you can use a common method:
public class AliveChecker {
public static boolean isAlive(int size) {
return size > 0;
}
}
public class Plant{
public boolean isAlive(){
return AliveChecker.isAlive(this.size);
}
}
public class Fish{
public boolean isAlive(){
return AliveChecker.isAlive(this.size);
}
}
Since Fishand Plant do not inherit from anything yet you can consider creating a superclass and extend from it:
public class LivingThing {
protected int size = 1;
public boolean isAlive() {
return size > 0;
}
}
public class Plant extends LivingThing {
}
public class Fish extends LivingThing {
}
This example uses inheritance to classify Plantand Fish into the superclass LivingThing. You can set the size for example in the constructor of the Plant or an instance method:
public class Plant extends LivingThing {
public Plant(int size){
this.size = size;
}
}
Your Model could then be:
public class Model{
private int countDeadFish() {
return countDead(this.fish);
}
private int countDeadPlants() {
return countDead(this.plants);
}
private int countDead(ArrayList<LivingThing> things) {
int totalCount = 0;
for(LivingThing thing: things) {
if(!thing.isAlive()) {
totalCount++;
}
}
return totalCount;
}
}
Use interface
public interface LiveObject {
boolean isAlive();
}
public class Fish implements LiveObject {
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Plant implements LiveObject {
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Model{
private int countDead(Collection<LiveObject> objects) {
int totalCount = 0;
for(LiveObject obj : objects) {
if(obj.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
private int countDeadFish() {
return countDead(this.fish);
}
}
Based on the comments it seems you can't modify Fish or Plant. Here's an approach to reduce duplication in countDead<Something> methods which does not require this.
Basically you want to count items in an array which satisfy certain criteria. With Java 8 you can capture this criteria in a predicate using lambdas or method references. You do not need inheritance or implementation of a certain interface for this.
private long countDeadFish() {
return countDeadItems(this.fish, Fish::isAlive);
}
private long countDeadPlants() {
return countDeadItems(this.plants, Plant::isAlive);
}
private <T> long countDeadItems(Collection<T> items, Predicate<? super T> isAlive) {
return items.stream().filter(isAlive.negate()).count();
}
You could create a utility method (in a utility class somewhere):
public final class Liveliness {
private Liveliness() {
}
public static boolean isAlive(final IntSupplier sizer) {
return sizer.getAsInt() > 0;
}
}
Your method then becomes:
public boolean isAlive(){
return Liveliness.isAlive(this::getSize);
}
Alternatively, use an interface Life:
public interface Life {
int getSize();
default boolean isAlive(){
return getSize() > 0;
}
}
This way, adding a getSize method and inheriting from Life will add the method.
Note, avoid the following antipattern:
if(test) {
return true;
} else {
return false;
}
Use return test.

Java inheritance ( local variable/ boolean in if)

I am studying the inheritance (Java), and I wrote the following code. The first part is the CarBase, and then I created a childclass 1, called Bus.
My idea is that first make a judgement if it is a bus, and by doing that, I need a boolean [if(isBus)], but when I wrote this code in Eclipse, there is a error message, said 'isBus can not be resolved to a variable'.
Could some one please tell me how to solve this problem? Do I need to declare the boolean variable first?
Another question is about the declaration of local variables.
In the getOnBus(0 method, I have a local variable called temp,I was taught that whenever using a local variable insided a method, I need to declare it first and then I shall be able to use it, but I saw someone use it directly like the following, I was wandering what's the difference between the two?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus(int p_amount) {
if(isBus) {
int temp = 0; // <===
temp = current_Passenger + p_amount; // <===
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
or if there is difference if I use it without declaring it?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if(isBus) {
int temp=current_Passenger+p_amount; // <====
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The code is as following
First Part CarBase(parent)
public class CarBase {
public int speed;
public String name;
public String color;
public int maxSpeed = 90;
// Method
public void speedUp(int p_speed) {
int tempSpeed = 0;
if (p_speed > 0) {
tempSpeed = speed + p_speed;
}
if (tempSpeed <= maxSpeed) {
speed =tempSpeed;
}
}
}
Second Part Bus (Child1)
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if (isBus) {
int temp = 0;
temp = current_Passenger + p_amount;
if (temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The point in using inherance is to abstract whether an object is a Car or a Bus, and write code that works no matter what is passed. To do so, you use abstract methods. Consider
abstract class Vehicle {
private int occupied;
public Vehicle() {
occupied = 0;
}
public abstract int getCapacity(); // number of passengers
public boolean board(int howmany) {
if (occupied+howmany <= capacity) {
occupied += howmany;
return true;
}
else
return false;
}
public void unboard(int howmany) {
occupied -= howmany;
}
};
class Car extends Vehicle {
public Car () { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 5; }
}
class Bus extends Vehicle {
public Bus() { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 32; }
}
you'd write every function to accept a Vehicle, and deal with it without the need to know if it is a bus or a car. (the following is a dumb function, just to give you an example)
void board_on_first_avaible(Vehicle[] x, int n) {
for (int i=0; i<x.length; x++)
if (x.board(n))
return true; // board ok
return false; // couldn't board on anything
}
Note that you should design your code so that the functions are declared, abstract in Vehicle, for both Car and Bus. Thus getOnBus() would be a bad idea
OK for the first point "isBus" is not declared, i can not see the point of checking in this method as you already know u are extending the CarBase but if you need to check you can do it like this
if(this instanceof CarBase)
for the second point there is actually no effect for the change
int temp=0; // <===
temp= current_Passenger+p_amount; // <===
first you initialize with 0 then you assign the new value to it
int temp=current_Passenger+p_amount;
here you initialize the temp with the value
You don't need to check if the Bus object 'isBus()' .... it IS a Bus, because you are defining the class as Bus!
So... if you were to create a new Bus object, you would say something like:
Bus BigYellowBus0001 = new Bus();
if you were to then say:
BigYellowBus0001.getOnBus(10);
You would NOT need to check if BigYellowBus0001 is a bus.... right?
In fact, you don't even need to name the method getOnBus().... it could just be getOn.
I think maybe you've gotten off on the wrong foot by deciding that Bus is a subclass of Car.
As for local variables, this just means variable that begin and end inside the method... so you did that nicely with your 'temp' variable.
To show that you understand how to access variables of the superclass from the child class, you could check the speed of the bus before letting people on:
public boolean getOnBus (int p_amount){
if(speed = 0){
int temp=0;
temp= current_Passenger+p_amount;
if( temp > max_Passenger){
return false;
} else{
current_Passenger = temp;
return true;
}
}
return false;
}
isBus is not declared that reason why you got this error
You doesn't need this check, because this method declared for Bus class and you are sure what it IS a Bus not a parent CarBase class (please use Vechicle instead of CarBase, it's much better on my opinion)
In Java 0 is default value for int, so you don't need to init variable before assign new value
So you can simplify getOnBus() like that
public boolean getOnBus (int p_amount) {
int temp = current_Passenger + p_amount;
if (temp > max_Passenger) return false;
current_Passenger = temp;
return true;
}
To test if an object is an instance of a class you can to use variable instanceof YourClass which evaluates to a boolean

How to inherit static field and change it's value?

I'm working on program/game where I have static utility class with params.
class ParamsGeneral {
public static final int H_FACTOR = 100;
public static int MAX_SCORE = 1000;
...
}
then I need to override this values in some specific cases, for example playing on map with limited score. So I did following:
class ParamsLimited extends ParamsGeneral {
public static int MAX_SCORE = 500;
// other params stay same
}
And the intended usage is following:
class Player {
ParamsGeneral par;
public Player() {
if(onLimitedMap()){
par = new ParamLimited();
}
}
public boolean isWinner() {
if(this.score == par.MAX_SCORE) {
return true;
}
return false;
}
}
I haven't actually tested this code, because IDE is complaining about calling static field through instance and also about field hiding. I clearly see that this code is stinks, so is there a way to achieve this or do I have to write each param class separately?
PS: I know I shoud make the default class abstract and use getters, I'm just curious if there is a way to make the values accesible statically.
You cannot override static members - in Java, neither methods nor fields could be overriden. However, in this case it does not look like you need to do any of that: since you have an instance of ParamsGeneral in the par variable, a non-static method would do what you need with the regular override.
class ParamsGeneral {
public int getMaxScore() {
return 1000;
}
}
class ParamsLimited extends ParamsGeneral {
#Override public int getMaxScore() {
return 500;
}
}
...
public boolean isWinner() {
// You do not need an "if" statement, because
// the == operator already gives you a boolean:
return this.score == par.getMaxScore();
}
I wouldn't use subclassing for a general game vs a limited game. I would use an enumeration, like:
public enum Scores {
GENERAL (1000),
LIMITED (500),
UNLIMITED (Integer.MAX_INT);
private int score;
private Scores(int score) { this.score = score; }
public int getScore() { return score; }
}
Then, when constructing a game, you can do:
Params generalParams = new Params(Scores.GENERAL);
Params limitedParams = new Params(Scores.LIMITED);
And so forth.
Doing it this way allows you to change the nature of your game while keeping your values centralized. Imagine if for every type of parameter you think of you have to create a new class. It could get very complicated, you could have hundreds of classes!
Simplest solution is to do this:
class ParamsGeneral {
public static final int H_FACTOR = 100;
public static final int MAX_SCORE = 1000;
public static final int MAX_SCORE_LIMITED = 500;
...
}
class Player {
int maxScore;
public Player() {
if(onLimitedMap()){
maxScore = ParamsGeneral.MAX_SCORE_LIMITED;
}
else {
maxScore = ParamsGeneral.MAX_SCORE;
}
}
public boolean isWinner() {
if(this.score == this.maxScore) {
return true;
}
return false;
}
}
No need to have an instance of ParamsGeneral, it is just a collection of static definitions for your game.
Have MAX_SCORE be private static with public static getters; then you can call ParamsGeneral.getMaxScore and ParamsLimited.getMaxScore and you'll get 1000 and 500 respectively

Categories