Android, couldn't make static getter setter property work? - java

I was trying this ...
public class Info {
private static Info ourInstance = new Info();
public static Info getInstance() { return ourInstance; }
private static int currentIndex;
public static void setCurrentIndex(int i) {
Log.d("DEV", "setter!");
currentIndex = i;
// do other work here
}
public static int getCurrentIndex() {
Log.d("DEV", "getter!");
return currentIndex;
}
private Info() {
Log.d("DEV", "class initialized no problem...");
currentIndex = 42; // just doesn't work, only sets the field
}
}
in any other class...
Info.currentIndex = 666; // just doesn't work
It just doesn't work - what could the problem be? Tried everything.

Why do you define the setter/getter if you are going to end up doing this?
Info.currentIndex = 666;
if so, then change currentIndex visibility to public...
or even better, be congruent with the code and do
Info.setCurrentIndex(666);

Related

How to square a the specified int value?

Im getting an error saying "value cannot be resolved"
public static MyInt square(MyInt a) {
double sqred = a.value;
MyInt sqrObjt = new MyInt(sqred);
return sqrObjt;
}
Here is my constructor
public MyInt(int value){
this.value = value;
}
I suppose the static method here is somewhere other than the class MyInt. You probably do not want a public static method, that's a more procedural approach to the problem rather than an Object-Orientated one. Instead add a non-static method to the class MyInt:
public MyInt square() {
return new MyInt(this.value * this.value);
}
Usage:
MyInt squared = someMyInt.square();
Make sure you have declared the int field value in your MyInt class. Also make sure to cast the double to an integer in your square method. It works fine for me.
public class MyInt {
int value; // make sure you don't forget to declare the field
public static MyInt square(MyInt a) {
double sqred = a.value; // you could've just done int sqred = a.value * a.value rather than have a double
MyInt sqrObjt = new MyInt((int) sqred); // don't forget to cast sqred to int
return sqrObjt;
}
public MyInt(int value){
this.value = value;
}
public static void main(String[] args) {
MyInt four = new MyInt(4);
MyInt fourSquares = square(four);
System.out.println(fourSquares.value);
}
}
I would imagine your main problem is the fact that you never declare value at any point during the class. But I expanded on the answer #junvar gave to include getters and setters for encapsulation. Here is how I would do it....
public class MyInt {
private int value;
void setValue(int value) { //setter
this.value = value;
}
int getValue() { //getter
return this.value;
}
int square() { //square method
int sqred = getValue() * getValue();
return sqred;
}
public MyInt(int value) { //constructor
setValue(value);
}
public static void main(String[] args) { //main to run it
MyInt testCase = new MyInt(3);
System.out.println(testCase.square());
}
}

Not sure about Singleton

If I have a singleton class like:
public class MySingleton(){
private static MySingleton istance;
private int element;
private MySingleton(){element = 10;}
public static MySingleton getIstance() {
if(istance == null)
istance = new Mysingleton();
return istance;
}
public void setElement(int i ){
element = i;
}
public int getElement(){
return element;
}
}
and I want to change element's value by calling
MySingleton.getIstance().setElement(20)
Will it change the element value for the istance? Here's an example:
... main () {
MySingleton.getIstance().setElement(20);
System.out.prinln(MySingleton.getIstance().getElement());
// It displays 10, why ?
I suggest you use an enum as it is simpler and thread safe (but not your getter/setter)
public enum MySingleton() {
INSTANCE;
private int element = 10;
public void setElement(int element) { this.element = element; }
public int getElement() { return element; }
}
MySingleton.INSTANCE.setElement(20);
System.out.prinln(MySingleton.INSTANCE.getElement()); // prints 20.
I'm not sure if your code block above was copied in or just retyped, but there were a few basic compilation issues I saw with it - when you're setting MySingleton in getInstance, you need to check capitalization. Also, your class declaration shouldn't have (parentheses). After fixing these two things and running basic main, I got 20.
This is the same as what you had - no synchronization or anything else, but on a single thread it doesn't seem necessary.
public class MySingleton{
private static MySingleton istance;
private int element;
private MySingleton(){element = 10;}
public static MySingleton getIstance() {
if(istance == null)
istance = new MySingleton();
return istance;
}
public void setElement(int i ){
element = i;
}
public int getElement(){
return element;
}
public static void main(String[] args) {
System.out.println(MySingleton.getIstance().getElement());
MySingleton.getIstance().setElement(20);
System.out.println(MySingleton.getIstance().getElement());
}
}
should have an output of
10
20
Im not sure if your code really work, how azurefrog say, make your code synchronized, and in youre line public static getIstance() { you need to set the return type.

error while calling a java Method

I am learning java. I am getting a lot of errors when I try to keep the methods, which I am trying to invoke, inside the main method.
I am trying to declare a couple of variables x,y. However, I want to invoke the math operations when specific methods are called, such as addMethod, subtractMethod, so on.
When I try to include the methods within the public method, I am getting an error.
package exampleclass;
public class MathLearning {
//declaring variables
static int x = 9;
static int y = 2;
public static void main(String[] args) {
int resu=0;
additMethod(resu);
subtMethod(resu);
multMethod(resu);
divMethod(resu);
private static void divMethod(int resu) {
resu = x+y;
System.out.println(resu);
}
private static void multMethod(int resu) {
resu = x-y;
System.out.println(resu);
}
private static void subtMethod(int resu) {
resu = x*y;
System.out.println(resu);
}
private static void additMethod(int resu) {
resu = x/y;
System.out.println(resu);
}
}
}
When I keep the methods outside the main method, I do not get an error.
package exampleclass;
public class MathLearning {
//declaring variables
static int x = 9;
static int y = 2;
public static void main(String[] args) {
int resu=0;
additMethod(resu);
subtMethod(resu);
multMethod(resu);
divMethod(resu);
}
private static void divMethod(int resu) {
resu = x+y;
System.out.println(resu);
}
private static void multMethod(int resu) {
resu = x-y;
System.out.println(resu);
}
private static void subtMethod(int resu) {
resu = x*y;
System.out.println(resu);
}
private static void additMethod(int resu) {
resu = x/y;
System.out.println(resu);
}
}
When I try to include the methods within the public method, I am getting an error.
You cannot have nested methods in Java1. Indeed, your second snippet has the methods in an appropriate location; outside of main.
1 (Aside) Well, I guess you technically can since you can declare classes within methods, meaning you can ultimately declare a method within another method:
void foo1() {
class X {
void foo2() {
...
}
}
...
}
You should very rarely have to do something like that, though.
In java, you cannot declare methods inside other methods (like you can, e.g., in python). Methods are defined under classes, like you do in your second code example.

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

Null pointer exception on getter setter in java

I have a getter setter class named SharedData.java . I am getting null pointer exception when I'm going to imply it on my code . Here is the SharedData class :
public class SharedData {
private static SharedData instance = null;
public SharedData() {
// randomizeServers();
}
// data to be shared
private double src_latitude = -1;
private double src_longitude = -1;
private double end_latitude = -1;
private double end_longitude = -1;
//Getter-Setters
public static SharedData getInstance() {
return instance;
}
public static void setInstance(SharedData instance) {
SharedData.instance = instance;
}
public double getSrc_latitude() {
return src_latitude;
}
public void setSrc_latitude(double src_latitude) {
this.src_latitude = src_latitude;
}
public double getSrc_longitude() {
return src_longitude;
}
public void setSrc_longitude(double src_longitude) {
this.src_longitude = src_longitude;
}
public double getEnd_latitude() {
return end_latitude;
}
public void setEnd_latitude(double end_latitude) {
this.end_latitude = end_latitude;
}
public double getEnd_longitude() {
return end_longitude;
}
public void setEnd_longitude(double end_longitude) {
this.end_longitude = end_longitude;
}
}
Here is my code :
SharedData sharedData ;
sharedData = SharedData.getInstance();
sharedData.setSrc_latitude(latitude);
sharedData.setEnd_longitude(longitude);
Can anybody please help me with this ? Thanks .
You never initialized sharedData, so its value is null, calling a method on it got your program to crash.
I think you're trying to use Singleton Pattern. Try the below:
private static SharedData instance = new SharedData(); \\ Initialize here
private SharedData() { // Make it private....
// randomizeServers();
}
// data to be shared
private double src_latitude = -1;
private double src_longitude = -1;
private double end_latitude = -1;
private double end_longitude = -1;
//Getter-Setters
public static SharedData getInstance() {
return instance;
}
SharedData.getInstance();
Returns null. Later you're trying to call a method on it:
sharedData.setSrc_latitude(latitude);
Which is illegal as reference to object is still null.
You don't instanciate the class, so getInstance() returns null.
At the start of your class, replace :
private static SharedData instance = null;
by :
private static SharedData instance = new SharedData() ; // creates a new instance
change private static SharedData instance = null;
to private static SharedData instance = this;
and make your class static
public static class SharedData {
Also , make the getters setters static..
Even using the singleton pattern you should instantiate the object SharedData at least once.
try this
SharedData sharedData = new SharedData();
sharedData = SharedData.getInstance();
sharedData.setSrc_latitude(latitude);
sharedData.setEnd_longitude(longitude);

Categories