I would like to make it so I can put integers defined by when I calling new Objectives(new Runnable(), "name here", int x, int y, int z) but I cant seem to do it. Again, the ints in the ENUMS will be put there when calling a new Objectives and the Location
Here's my code so far:
package me.terturl.com.Objectives;
public enum Objectives {
MECH(new Runnable() {
#Override
public void run() {
}
}, "Mech", Location loc, int x, int y, int z);
private String name;
private Location loc;
private int x;
private int y;
private int z;
public objectives(Runnable run, String name, Location loc, int x, int y, int z) {
this.name = name;
this.loc = loc;
this.x = x;
this.y = y;
this.z = z;
}
public String getName() {
return name;
}
public Location getLoc() {
return loc;
}
}
All enums are constants. You cannot specify parameters for new instances of an enum. Instead, use a class to construct new objects based on the given parameters.
Example of an enum in usage:
enum WeekDay { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(0); public final int id; WeekDay(int id){ this.id = id; } }
Example of a class that may be used for this case:
package me.terturl.com.Objective;
import org.bukkit.Location;
public class Objective {
private String name;
private Location loc;
private int x, y, z;
Objective(Runnable run, String name, Location loc, int x, int y, int z) {
this.name = name;
this.loc = loc;
this.x = x;
this.y = y;
this.z = z;
}
public String getName() { return name; }
public Location getLoc() { return loc; }
}
Edit: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else. Hence, enums will not achieve what you are looking for - Storing details of an objective. Instead use the above class and create a Manager Class to handle your objectives.
However, enums can implement interfaces, when applicable:
interface MajorObjectWrapper{
public Object getMajorObject();
}
enum Utility implements MajorObjectWrapper {
VAULT("Gold"),
//...
LOCK(new Lock());
#Override public Object getMajorObject(){ return obj; }
private Object obj;
Utility(Object obj){ this.obj=obj };
}
{
MajorObjectWrapper wrapper=Utility.VAULT;
System.out.println(wrapper.getMajorObject());
// You will get: "Gold"! :)
}
Thanks to #nrubin29 for citation on implementing interfaces with enums.
Specified by:
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
PS: Your package declaration makes the absolute path of the class me.terturl.com.Objectives.Objectives. Consider refactoring the package declaration as me.terturl.com or me.terturl.com.objectives. Semantics :)
I don't think an enum is what you're looking for. From the Oracle Java tutorial's enum page here:
An enum type is a special data type that enables for a variable to be a set of predefined constants.
Constants. So making new instances really doesn't make sense. And that's also enforced at the language level. JLS section 8.9.2:
It is a compile-time error if a constructor declaration in an enum declaration is public or protected (ยง6.6).
In an enum declaration, a constructor declaration with no access modifiers is private.
So there's your first problem. You can't have a public enum constructor.
Second, you're slightly misunderstanding how enum constant constructors work. When you do something like
MECH(...)
You're effectively calling a constructor. And you can't do things like have int x in a constructor call. You're going to have treat it like any other constructor, which means either you get to put a method call there or some other expression that evaluates to something. Your first two parameters were OK, but the rest of them, not so much.
For example, if I wanted to make a new String(), I can't do this:
String s = new String(String putStringHere);
Similar logic applies to your code.
Honestly, I'm a little confused why you're using an enum. Seems to me like a regular old class would do just fine.
(also, probably a typo, but your constructor should be capitalized)
Related
In Java, I feel that using Private when declaring an attribute and not declaring a Setter method for it gives the same outcome as using Final when declaring the attribute, both allow the variable to stay constant.
If that is the case, what is the benefit of using Final in this scenario?
Even without a setter other methods in the class can change the attribute so it's a completely different concept.
Many would argue it's not a good thing to do (it adds "side effects" to your program) but it's still possible.
Assumed you are talking about variables, the keywords final and private define different characteristics.
The keyword final denies any changes to the variable and throws compilation errors when modified or changed. However, without specifying public or private, with the default package-private access modifier, it could be accessed by other classes in the same package once initialized (text with bold fonts are corrected by #charsofire and #MC Emperor).
On the other hand, the keyword private rejects the idea of being called by other classes, even in the same package. But it could be changed and modified by methods in the same class, even without setter or getter methods.
For example in the same class of the same package:
public class Student {
private int score;
final int id;
public Student(int id, int score) {
this.id = id;
this.score = score;
}
public void modifyGrade(int newScore) {
// Accepted
this.score += newScore;
}
public void modifyID(int id) {
// Rejected
this.id = id;
}
}
And in different class of the same package:
public class School {
public static void main(String[] args) {
Student student = new Student(0, 35);
// Accepted
System.out.println(student.id);
// Rejected
System.out.println(student.score);
// Accepted
student.modifyGrade(29);
// throws exception
student.id = 5;
// Not visible
student.score = 29;
}
}
Hope this answer helps you well,
and many thanks again to both #charsofire and #MC Emperor, who helped to clarify significantly in this answer.
The answer is Encapsulation
Consider this.
public class Point
{
int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
//no getters or setters needed, I can just modify or read x and y directly.
}
public class FinalPoint
{
public final Point point;
public FinalPoint(int x, int y)
{
this.point = new Point(x, y);
}
//no getters needed, I'll just read point since it is public
}
Right now, this FinalPoint has a final Point as an instance field. On the one hand, it means that that instance field cannot be reassigned. However, the fields of that instance field can definitely be reassigned.
For example.
FinalPoint p = new FinalPoint(1, 2);
p.point.x = 4; //I have now modified state! final did not protect us here
The final keyword is powerful, but it does not mean that your data is unchangeable. It only means that that surface level reference is unchangeable - it will force a reference to always point to the same object. That does not stop the object its pointing to from changing it's internal state as much as it wants. The only guarantee final makes is that you always be pointing at the same object.
Which brings us to encapsulation. Encapsulation was created to solve this exact problem and more.
Consider this.
public class EncapsulatedPoint
{
private Point point;
public EncapsulatedPoint(int x, int y)
{
this.point = new Point(x, y);
}
public int getX() { return this.point.x; }
public int getY() { return this.point.y; }
}
Now, because I have encapsulated Point and exposed only the data I can safely expose, I have protected myself from modification. It is impossible to change this object (without using reflection or other hacks the designers are actively removing). It truly is Immutable.
Of course, Encapsulation is not superior to using final. There is a time and a place for both. Knowing when and where allows you to make your software secure.
Private variables will never access from the outside of the class and Final will never change by taking input from the user.
I created some classes with inheritance concept, I have the main class for my application, that is called modulo, which corresponds to an module, and also some other classes called moduloLedRGB, ModuloSwitch, and ModuloDimmer, these 3 classes all extends the class modulo which has just the common arguments for modules like, id, name, Module type, and ipAdress. But, when I try to cast a module to one of those 3 childs classes I get an exception that says I cannot cast Modulo to ModuloSitch or ModuloLedRGB...
This is where I get the error:
switch (modulo.getModulo()){
case "RGB":
ModuloLedRGB rgb = (ModuloLedRGB) modulo;
rgb.setProgress(c.getDouble(c.getColumnIndex("progress")));
rgb.setProgressRed(c.getDouble(c.getColumnIndex("progressRed")));
rgb.setProgressGreen(c.getDouble(c.getColumnIndex("progressGreen")));
rgb.setProgressBlue(c.getDouble(c.getColumnIndex("progressBlue")));
break;
case "Dimmer":
ModuloDimmer dimmer = (ModuloDimmer) modulo;
dimmer.setProgress(c.getDouble(c.getColumnIndex("progress")));
break;
case"Switch":
ModuloSwitch sw = (ModuloSwitch) modulo;
break;
It says I cannot cast modulo that is an object corresponds to the class Modulo, to ModuloRGB.
getModulo returns a string that says me which kind of Module this is.
package br.com.andrey.projetointegradoapp;
/**
* Created by andrey on 04/08/2016.
*/
public class Modulo {
private long id;
private String nome;
private String ModuleIpAdress;
private String modulo;
public String getModulo() {
return modulo;
}
public void setModulo(String modulo) {
this.modulo = modulo;
}
public String getModuleIpAdress() {
return ModuleIpAdress;
}
public void setModuleIpAdress(String moduleIpAdress) {
ModuleIpAdress = moduleIpAdress;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
This is the Modulo Class.
and this is ModuloLedRGB class:
package br.com.andrey.projetointegradoapp;
/**
* Created by andrey on 16/12/2016.
*/
public class ModuloLedRGB extends Modulo {
private double progress;
private double progressRed;
private double progressGreen;
private double progressBlue;
public double getProgressRed() {
return progressRed;
}
public void setProgressRed(double progressRed) {
this.progressRed = progressRed;
}
public double getProgress() {
return progress;
}
public void setProgress(double progress) {
this.progress = progress;
}
public double getProgressGreen() {
return progressGreen;
}
public void setProgressGreen(double progressGreen) {
this.progressGreen = progressGreen;
}
public double getProgressBlue() {
return progressBlue;
}
public void setProgressBlue(double progressBlue) {
this.progressBlue = progressBlue;
}
}
Any ideas for why am I getting this exception? since the child extends the main class I think I should be able to cast it down, not?
Based on the comments, it appears that you misunderstand the nature of casting.
When you say
class Modulo { ... }
class ModuloLedRGB extends Modulo { ... }
Subclassing defines an is-a relationship; every ModuloLedRGB is also a Modulo. But that doesn't work both ways.
If you create an object with
new Modulo()
then it is a Modulo, but not a ModuloLedRGB. If you create it with
new ModuloLedRGB()
it is both a ModuloLedRGB and a Modulo. Saying it's a Modulo means that you can assign a variable of type Modulo to it, or use it as a Modulo parameter:
ModuloLedRGB x = new ModuloLedRGB();
Modulo y = x; // this is legal, but the object's class doesn't change
y is a reference to the ModuloLedRGB object. But note that although y is declared as Modulo, it still refers to the same object, whose class is ModuloLedRGB, because that's the way the object is created.
That's why you can use downcasting. Say you later use the expression
(ModuloLedRGB)y
At this point, the compiler knows only that y (if not null) is a Modulo; it could be an object of class Modulo, ModuloLedRGB, ModuloSwitch, or anything else. So at run time, the code checks to see what kind of object it's actually referring to. Since the example above set y to an object created as a ModuloLedRGB, the cast is successful. But if y were set to some other object that wasn't a ModuloLedRGB, the cast throws an exception.
This cast doesn't change an object, and it doesn't create a new object. It just says "Make sure the object is of class ModuloLedRGB, and then treat it as a ModuloLedRGB so that we can access methods and instance variables that are particular to a ModuloLedRGB".
It looks, however, that you're trying to convert the object by changing its class. You've created an object whose class is Modulo, and you're trying to come up with some new object whose class is ModuloLedRGB. You can't do that with a cast. If you have a Modulo and you want to create a ModuloLedRGB, you will have to create a new object with new ModuloLedRGB(), somewhere. One common way to do this is to write a constructor:
class ModuloLedRGB extends Modulo {
public ModuloLedRGB(Modulo m, maybe other parameters) {
// copy the instance variables from "m"
this.field = m.field;
this.anotherField = m.anotherField;
// set the new instance variables
this.newField = maybe a parameter or some other computation;
...
}
or write a static factory method to create a new ModuloLedRGB from a Modulo. But you'll have to create it, and you'll have to write the code to create it. You can't "convert" it from a Modulo. There's no such thing in Java.
I'm working on a java based game with a friend and I've noticed he's taking an approach that concerns me, in terms of maintainability.
For a class representing a playable Character, instead of just creating 1 method which sets an object's property, he's creating separate methods which set the property to a specific value.
Which of these 2 options would be the best to follow going forward?
Option 1
public void runFast() {
this.character.speed = 5.0f
}
public void walk() {
this.character.speed = 2.0f
}
public void stop() {
this.character.speed = 0.0f;
}
Option 2
public void setSpeed(float speedTemp) {
this.character.speed = speedTemp;
}
Why not use an enum to set the speed - then you can still have
void setSpeed(Speed speed) {
this.character.speed = speed.getAmount();
}
with:
enum Speed {
FAST(5.0f), WALK(2.0f), STOP(0.0f);
private final float amount;
private Speed(flaot a) { this.amount = a; }
public float getAmount() {
return amount;
}
}
That way, you can quickly update the values, but still have a predefined amount. Its flexible and easy to maintain. You might want to save the enum instead of the float.
My Solution would be to use Enums instead,
it is cleaner and has more context and easily extensible if you have more to do with your speed maxHeartRate in the future.
public class Character {
private Speed speed;
public Speed getSpeed() {
return speed;
}
public void setSpeed(Speed speed) {
this.speed = speed;
}
};
public enum Speed {
STOP(0),
RUN(5.5),
WALK(2.5);
double value;
Speed(double value) {
this.value = value;
}
public double getValue() {
return value;
}
};
IMHO the best option would be to declare constants/enums, and use the option 2.
Example (constants) :
public static final float STOP = 0.0f;
public static final float WALK = 2.0f;
public static final float FAST = 5.0f;
setSpeed(STOP|WALK|FAST);
Example (enums) :
public enum Speed
{
FAST(5.5f),
STOP(0),
WALK(2.5f);
float value;
Speed(float pValue)
{
this.value = pValue;
}
public float getValue()
{
return this.value;
}
}
setSpeed(Speed.FAST);
It depends. For example
Are speeds limited to a few predefined values? In that case using an enum would be a good solution.
Is walking / running / stopping going have side effects other than just setting the speed? As a contrived example, starting to run might cause the character to drop an item it's holding, or stopping might cause the character to skid a little. In this case having separate methods might make sense.
Or maybe there are only a few predefined states, but depending on the environment running speed might be different.
What it comes down to is: Which way of conceptually modeling the properties of your character works best for your game logic / physics? Work this out and then base the interface of your classes on that. Don't get too hung up on the exact API early on, this sort of stuff is pretty easy to refactor.
getter and setters are useful when you want that your code is readble and for avoiding that public class fields can be used in the wrong way from another classes.
This example show how is important.
CLASS A:
public class ClassA{
// in the body class
private String fieldClass1;
//classic setter
public void setfieldClass1(String f1)
{
fieldClass1 = f1;
}
}
CLASS B:
public class ClassB{
// in the bodyclass
public String fieldClass2;
//classic setter
public void setfieldClass2(String f2)
{
setfieldClass2 = f2;
}
CLASS C:
public class ClassC{
//in the body of the class this method use class a and class b
public void calc()
{
ClassA aObject = new ClassA();
ClassB bObject = new ClassB();
ClassA.fieldClass1 = 5 + 5; // illegal expression for the compiler and costrain the developer to use setters
ClassB.fieldClass2 = 8 + 8; // legal expression
}
}
This mean that you must define a "modifiers logic" (protected, private, public) before make setters and getters. Define before the modifiers and after define the setters and getters.
How do I build a copy constructor that receive another point (x,y) and copy its values ?
I decide a signature: public Point1 (Point1 other) , but I don't know what to write in it...
The Point class looks like:
public class Point1
{
private int _x , _y;
public Point1 (Point1 other)
{
...
...
}
//other more constructors here...
}
I tried:
public Point1 (Point1 other)
{
_x = other._x ;
_y = other._y;
}
But I almost sure I can do it better..
thnx
Nope, your attempt of
public Point1(Point1 other)
{
_x = other._x ;
_y = other._y;
}
is absolutely fine... (I've corrected the parameter type.)
I'd be tempted to make _x and _y final, and make the class final, but that's because I like immutable types. Others definitely have different opinions :)
Cloning on an inheritance hierarchy is slightly trickier - each class in the hierarchy has to have a relevant constructor, pass whatever argument it's given to the superclass constructor, and then copy just its own fields. For example:
public class Point2 extends Point1
{
private int _z;
public Point2(Point2 other)
{
super(other);
this._z = other._z;
}
}
That's not too bad on the implementation side, but if you want to faithfully clone a Point2 you need to know it's a Point2 in order to call the right constructor.
Implementing Cloneable allows this to be done a bit more simply, but there are other things to consider around that... basically cloning objects isn't as simple as it might appear :) (I'm sure there's an entry in Effective Java for it. If you don't have a copy, buy one now.)
Although the question is quite old but here is an example of copy constructor
public class CopyConstructor {
private int id;
private String name;
public CopyConstructor(int id, String name) {
super();
this.id = id;
this.name = name;
}
public CopyConstructor(CopyConstructor copy) {
id = copy.id;
name = copy.name;
}
}
Copy constructor is much easier to implement and we don't need to
implement Clonable interface.
The clone method returns object which needs to cast , we don't need to cast copy
constructor.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Property and Encapsulation
NEWB Alert!!
I am starting with Android and Java and I am starting to understand it but I am wondering why I should use getters and setters and not just public variables?
I see many people make a private variable and create a get and set method.
What is the idea here?
Its called encapsulation and the concept is central to object oriented programming. The idea is that you hide the implementation of your class and expose only the contract i.e. hide the how and only expose the what. You hide the variables by making them private and provide public setters-getters and other public methods which the clients invoke to communicate with your class. They are not tied to the actual implementation of the methods or how you store your variables.
For example, suppose you had this class where you stored a phone number as a Long object:
public class ContactInfo {
private Long phoneNo;
public Long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = phoneNo;
}
}
Since the clients of the class only see the getter/setter, you can easily change the implementation of the class/methods by switching the phone number representation to a PhoneNumber object. Clients of ContactInfo wouldn't get affected at all:
public class ContactInfo {
private PhoneNumber phoneNo;
public Long getPhoneNo() {
return phoneNo.getNumber();
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = new PhoneNumber(phoneNo);
}
}
public class PhoneNumber {
private Long number;
public PhoneNumber(Long number) {
this.number = number;
}
public Long getNumber() {
return number;
}
}
The OOP concept involved is encapsulation (google it).
Some of the advantages are: you can specify different access level for setters (mutators) and getters (accessors), for example public getter and private setter. Another advantage is that you can add another code other than changing or retrieving the value. For example, you may want to check the validity of the set value, or you want to throw exceptions or raise some events in response to changing the variable to certain value. If you implement these inside an accessor or mutators, you can also change their implementations without changing any code outside of the class.
I believe the idea is "information hiding" http://en.wikipedia.org/wiki/Information_hiding
It also serves to control the access to variables (provides an interface). For example, you can provide a getter but not a setter, so that they may be read but not written. Whereas if everything was public any thing could read and write to the variables.
Also important is any checking/validation need to set a variable. For example you have a String name that is not allowed to be empty but if it is public it could easily be forgotten and set as name = "". If you have a setter such as public boolean setName(String newName) you can check newNames length and return true or false if it passes and is set or not
The concept is called encapsulation.
What it attempts to do is to separate the inner structure of a class from its behaviour.
For example, suppose a class like this
public class Point{
private float x;
private float y;
public float getX(){
return x;
}
public float getY(){
return y;
}
public float distanceToZero2(){
return x*x + y*y
}
public float getAngle(){
//havent considered the x = 0 case.
return atan(y/x);
}
public boolean isInFirstQuad(){
return x>0 && y>0;
}
}
In this case, encapsulation hides the inner structure of the class, and exposes only the operations available to a Point. If you dont like it, you can change its inner structure and mantain its behaviour (for example, changing carthesian coordinates to polar coordinates).
Anyoune who uses this class wont care about it, he /she will be happy that they have a Point class with this functionality.
Asides the encapsulation, you can also control the value get or set to your variable in some cases. For example, you want to validate the value of an age variable which should be >=1
class Person {
private int age = Integer.MIN_VALUE;
public void setAge(int age){
if(age>=1)
this.age = age;
}
public int getAge(){
return age;
}
}