What is meant by property in java ? - java

Does it differ from methods? Like arrays have a property - length and so array.length gives the length of array whereas array.length() gives an error

A better term to use for properties is a field. Basically, a field is a variable, while a method is where you have the "meat" of your code. For these examples, I'll be using the object "Book".
Fields can be classified as "instance" variables meaning that they are different for each object, or they can be classified as "static" variables, which means that they are universal for the project.
private int pages;
private static int amountOfBooksInTheWorld;
The number of pages is specific to a certain book, a specific "instance" of the book object. The amount of books in the world is obviously not specific to one book; therefore, it is "static", universal, for all books. Instance variables are called by stating objectname.variablename, while static variables are called by classname.variablename.
javahandbook.pages
Book.amountOfBooksInTheWorld
Now for your second question, methods, those things with the parentheses, are usually classified into these groups: constructor, accessor, mutator, and static methods. All methods have "parameters" and "return types". The parameters are basically inputs. The return types are the outputs (if there are any). Methods are called by objectname.method(), unless they are static, where they are called by classname.method().
Constructors are what you use to create your object. They usually are the ones which "initialize" all the instance variables for the object, that is to say, they basically tell them what they start as. These methods have no return type. Constructors are probably the most different method type from the rest, but are very important.
public Book(int p) {
pages = p; //We use "=" to initialize our variables (left becomes the right)
}
In action...
Book javahandbook = new Book(100); //A new book has been created!
Accessor methods are what other classes use to find out what are the instance variables of a particular object. These specify a return type of either boolean (a fancy name for true or false), floating point numbers (double-precise return types that include double and float), regular numbers (integer return types such as byte, short, int, or long), or even other objects. The return type is what you get "back" when the method is done doing its thing. Keep in mind that the object being referred to in the method call is the "implicit parameter", meaning that it can be referred to using "this". It sounds wierd. I'll show you an example.
public int getPages() {
return (this.pages);
}
In action...
int test = javahandbook.getPages();
System.out.println(test); //This will return the amount of pages
//Note that what I did with the 2nd line was bad coding practice, but it works in this scenario
Mutator methods change the instance variables. Their return type is "void".
public void ripPages(int rippedpages) {
this.pages = this.pages - rippedpages;
System.out.println("HULK SMASH");
}
In action...
javahandbook.ripPages(300);
Static methods are the ones that are universal, not on a per object basis. They can have any return type.
public static int countBooks(List<Book> books) {
return (books.size);
}
In action...
public int howmanybooksinthislist = Book.countBooks;
Put all of them together and you get...
public class Book {
private int pages;
private static int amountOfBooksInTheWorld;
public Book(int p) {
pages = p;
}
public int getPages() {
return (this.pages);
}
public void ripPages(int rippedpages) {
this.pages = this.pages - rippedpages;
System.out.println("HULK SMASH");
}
public static int countBooks(List<Book> books) {
return (books.size);
}
I know this was a bit too lengthy, but I hope it helps!

Properties/Fields are variables in a class. For example:
public class Employee {
private String name;
private int salary;
public getName(){return this.name};
}
In the class above, name and salary are properties of an instance of the class (object of the class) while getName() is a method.

Properties are the adjectives describing an object, in this example "how many elements it has". Properties are set to define variable aspects of instance of the object, either directly (if allowed) or as the result of some action, and then they may be examined when using the object.
Methods are the verbs provided to do something with the object, for example "add a new element". These actions may utilize properties, and may alter them, as well as doing other things (whatever purpose the creator defines). Methods may also accept adverbs in the parenthesis that further effect how they operate, thus the different syntax with "()"; for example information to "add in the new element".
While methods are more complex and versatile mechanisms, a complex object might not have pre-calculated (cached) "x.length" type properties always already available to examine and thus the object might provide a method "x.length()" to get the information. That method might have to evaluate complex aspects of an object to figure out "length", and either set it and or give it back, blurring the line between a property and that more simple use of a method.
Tangent on "field", "property" and "properties": while the technical term "field" very specifically identifies a data storage element attached to an object, the term "property" is acknowledged by the core group at http://docs.oracle.com/javase/tutorial/information/glossary.html. A property is more abstract, but logically synonymous to field when considered in comparison to a method. Logically different than field/property in this comparison, though related, is a "properties" set which is a static gathering of initial settings of property values for an application (a collection of code presented for a designated use), most often placed in a file ".properties" named and stored at a location agreed upon by the application - though these might also be gathered in any other storage location like a database.

array.length is accessing a field inside the object, while array.length() is attempting call a method call length(), and since the method does not exist, it gives an error

To understand properties and methods, think of an apple. An apple can be different colours, like red, yellow, etc. An apple can also have varying sizes. Both of these traits, colour and size, are properties of an individual apple; they describe the apple.
A method is different. It describes something an apple can do, like grow and ripen. Some methods, however, can also represent properties, and simplify reading those properties.
For example, an object representing a pen might have a certain amount of ink left. When requesting how much ink is left, the pen object would need to verify that there is any, and refill the pen if not, before returning how much ink there is.
To directly answer your question, properties and methods are very different. Properties hold data about an object, but methods hold data about what an object can do. Something like the length of an array is a property because it describes the array itself, not what the array can do.
This and other definitions of some useful terms are given here.

Related

How to return one of two types in a getter method?

I'm trying to program a board for a game. The board has 25 fields, and each field can either contain a base or 4 different sizes of rings.
public class Field {
private Base base;
private Ring[] rings;
public Object getPieces() {
if (base == null) {
return rings;
} else {
return base;
}
}
}
I programmed the setter methods so that a Base only can be set if rings is null, and that a Ring only can be set if base is null.
The problem is that in order to paint the board, my view needs the contents of Field, which is either a Base or a Ring[]. I find it hard, however, to allow the method to return both types. Right now, I'm returning the contents as Object, but this is bad practice.
Is there any way in which I can allow my method to return both types?
If not, is there a way in which I can store my pieces more efficiently that allows me to return them as one type?
Also, Base and Ring both extends the same superclass Piece, so I could return them as pieces instead, but then I would still have the problem that one of the two return types is an array where the other is not.
You could return an array of pieces. If you need to return only the base, then you just put it inside an array of pieces which will be the only element. Otherwise you return the array or rings.
So, your method will be like this:
public Piece[] getPieces() {
Piece [] toReturn;
if (base == null) {
toReturn = rings;
} else {
toReturn = new Piece[]{base};
}
return toReturn;
}
Consider that if you implemented new methods in the Base or Ring classes, then those methods canĀ“t be called because you defined that the objets inside the array are from the Piece class, unless you make a cast - if the array has only one element it is a Base, otherwise is a Ring. This is like an implicit instanceOf, so be very carefull. The use of instanceOf should make you check if there is a better way of solving the problem!
You need to work out what you want to do with the things that this method returns and then create a superclass for them. This may be the Piece class, but it could be a Drawable or something else. Without knowing what you are doing it is hard to give a real answer.
As to your array or object you have two options. Again what is right for you is hard to give based on the information given. Either the getPieces can a collection of some sort regardless (array, List, Set etc) even if it is a collection of one, or your Piece (or Drawable or what ever) could work regardless of if what backs it is a single Piece or a collection of Pieces.
You should be attempting to encapsulate the logic rather than just handing things out willy-nilly. Again I don't know your application, but say in the case of a Bank rather than have a getBalance and setBalance you have a deposit, withdraw and display(onThis).
In the class where you are calling your getter, you could try using the instanceOf
Field field = new Field();
Object returnObject = field.getPieces();
if(returnObject instanceOf Base){
// add to Base
} else if(returnObject instanceOf Rings){
// add to rings
}
Unless you have a strict programming guidelines, in the long run the code can end extremely long and ugly, and after some point of time you might not be able to debug the code as well. So be careful.
I would say setting null is even a more "badder" practice than methods returning Object instances. As long as you can help it, don't set anything as null.
Your architecture propably violates the Tell, Dont Ask principle: The Board asks Field for it-s internal state getPieces().
If you reformulate this to: The Board tells Field to draw itself you find out that the drawing logic should belong to Field and not to board. This way there is no more need for the board to know the implementations detail that a field may contain a base or rings.

In Javassist, is return order guaranteed?

Javassist's CtClass has a few methods, such as getFields() and getMethods(). I was wondering if these methods offer any guarantee as to their ordering.
Specifically, I'd like to know if using getFields() on a class will produce and array of CtFields where the first field in the array is the first field declared in the file and so forth. So, is this order guaranteed? If not, is there anything that can offer this guarantee? The javadocs give no information on the matter. I've tried annotations that carry order (e.g. #X(1) private int first;), but it'd be easier if I could reflect this sort of thing without the need for annotations?
If it's still not clear, I'd like something like:
public class Class {
public int x;
public float y;
public Object z;
}
to produce an array of CtFields specifically and consistently ordered x, y, z.
If you look at one of the implementations of CtClass, like CtClassType, you will see that getMethods() is implemented that way:
public CtMethod[] getMethods() {
HashMap h = new HashMap();
getMethods0(h, this);
return (CtMethod[])h.values().toArray(new CtMethod[h.size()]);
}
According to the HashMap javadoc:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
So, you have absolutely no guarantee in what order you will get the methods.
For the fields, the code is a lot more complicated, but it seems that the raw class file is read as an InputStream:
DataInputStream in = new DataInputStream(
new FileInputStream(args[0]));
ClassFile w = new ClassFile(in);
And the fields are created as they are read from this stream:
fields = new ArrayList();
for (i = 0; i < n; ++i)
addField2(new FieldInfo(cp, in));
So, the fields are created in the order they are in the class file.
However, reading the JVM Specification and the Java Language Specification, I see no reference to the fields order in the generated class; this sentence from the Java Specification even seems to indicate that the fields order is not important:
Using their scheme, here is a list of some important binary compatible changes that the Java programming language supports:
[...]
Reordering the fields, methods, or constructors in an existing type declaration.
So I think that you have absolutely no guarantee on the fields order too.
I tried to run javassist.tools.Dump on a test class I created with a large number of fields and methods, and it seems that fields and methods are printed in the source order, but I still think that nothing guarantee it.

Best strategies when calling a method that should modify more than one variable

I am pretty new to Java, I have to convert C/C++ code to Java and I am running into obstacles. Because of the way variables are passed to the methods, their modification in the method is not straightforward, and I have no idea what is the most reasonable approach to take. Sorry for the pseudocode examples, I hope they will clearly explain what I am talking about without delving into unnecessary details.
I need something that would be equivalent to C
ModifyMyString(type1 &t1,type2 &t2);
(return type doesn't matter, it can be void) as I need the function to modify both t1 and t2.
I can easily modify one of the variables, say t1, by declaring in Java
type1 modifyMyString(type1 t1, type2 t2);
and assigning the returned value to
t1 = modifyMyString(t1,t2);
but it is only half of a success, as the new value of t2 is lost.
I can declare new class
class JustToPassTwoVariables {
type1 t1;
type2 t2;
JustToPassTwoVariables(type1 tt1, type2 tt2) { t1 = tt1; t2 = tt2; }
}
and do something like
JustToPassTwoVariables jtptv = modifyMyString(JustToPassTwoVariables(t1,t2));
but I feel like it is clumsy and makes the code unreadable.
In desperation I could also resign the idea of using a modifyMyString method, and repeat all the code locally in each place I would call modifyMyString - but it makes even less sense than using JustToPassTwoVariables class.
Is there a correct (or at least widely used, accepted as a standard, whatever) strategy to code such things in Java?
The recommended way in java is (in some people's opinion the clumsy way) to create a class containing the two fields and return an instance of that class.
I feel that it is much less clumsy if you stop and think about what the method is actually doing, and taking care to properly name both the method and the class returning the two values.
The simple answer is no. This sort of feature is not allowed in Java.
The correct way to do it is to pass in the object to be modified not the two variables. After all in virtually all cases those variables are already wrapped in an object, in cases where they aren't they often easily can be.
Either split the function into two functions and call it once for each variable, or wrap the variables into an object and pass that object into the function.
Don't forget Java allows Inner Classes which makes this sort of thing less painful.
You can't return two values from a method in java. The way is to return an object and set all the values in it. i.e. In your case, you need to create a value container class i.e. say Result class that will have two fields storing the type1 and type2 value in it. The return type of the method would be of value container object type i.e. say Result instance with two fields in it - type1 and type2
Example :
Result result = modifyMyString(t1,t2);
result.getT1(); //gets t1 value
result.getT2(); // gets t2 value
Please learn about setters and getters in Java to work on the class or object level fields
In Java if you want to do this you would generally make type1 and type2 into object whose values can be modified. The method can then modify the values of the parameters to get the desired effect. For example :
void myMethod(type1 arg0, type2 arg1) {
arg0.setValue(newValue0);
arg1.setValue(newValue1);
}
If type1 and/or type2 do not have any way of changing their values (e.g. they are of type String) then you would either make a wrapper class for each of them e.g.
class Type1Wrapper {
private type1 type1;
type1 getType1() {
return type1;
}
void setType1(type1 newType1) {
type1 = newType1;
}
}
or you would make a wrapper for both of the types simultaneously like you have in your question (although the method return type will be void and the method will modify your wrapper's values)
There are several methods to modify a group of objects "of the same type/class". The simplest of them being, add them to a "list" pass that list to your modification function, do whatever modifications/additions/deletions etc.. The list reference will be automatically available outside with the "changes made in the called function" .
So, you can do
List<String> l = new ArrayList<String>();
l.add("Hello");
l.add("world");
ModifyMyString(l);
// here also l = "hello" , "world" , "added"
public void ModifyMyString(List l)
{
l.add("added"); // now l = "hello" , "world" , "added"
}
Java is an OO language so to get the best out of it you should look to an OO solution. It's hard to give you a definite solution with this abstract example but this is how I would approach this.
You mention that t1 and t2 both need to be updated by this modify procedure/method. Also that they need to be updated at the same time, if they were unrelated then you could just call modify on each string in turn. If these two strings are related like this then it's likely they belong to the same type.
So we need a class containing type 1 and type 2.
public class TypeContainer
{
private String type1;
private String type2;
.. getters and setters
}
Obviously you'll want a better class name.
You suggest something similar yourself but call it JustToPassTwoVariables. This is missing the point of OO. You could write a simple wrapper like this and pass it to some other method to modify the values but a more OO approach would be to add the modify method to this class itself.
...
public void modfiy(String val1, String val2)
{
type1 = val1;
type2 = val2;
}
...
I'm not sure what your modify is trying to do but in this case I would probably have these as two separate setter methods. This is quite an abstract example!
Basically I would avoid having the modify method in some other unrelated class. You should look to group common related attributes into classes and then write methods in those classes for any actions you need to take (such as modify).
Trying to convert a procedural C program into an OO Java program sounds like a PITA. It's a complete paradigm shift. Having said that I have seen automated conversions which while technically Java are still very procedural. Not very pretty and hard to maintain but was done for political reasons.
Java discourages this strategy beacause in-variable should be immutable, but if you have to migrate from C/C++/C# and you have a lot of "void function with parameters passed as in/out", you can create a Custom "Reference" class like this and you can incapsulate the original object.
public class CustomRef {
public Object internal;
public CustomRef(Object object) {
this.internal=object;
}
}
then when you call
CustomRef ref1= new CustomRef(myParams1);
CustomRef ref2= new CustomRef(myParams2);
myFunction(ref1, ref2);
myParams1 = ref1.internal;
myParams2 = ref2.internal;
the function is
void myFunction(CustomRef ref1, CustomRef ref2) {
Object param1 = ref1.internal
// a lot of code
ref1.internal = param1;
}
really discouraged way ... such as using ArrayList, arrays [] to "pass by reference".
NOTE: this way is a waste of resource; CustomRef instance should be reused through object pool (another discouraged way).
I would use a StringBuffer. You can initialize it with a String and convert it back to a String

getter method vs directly using input param

I have come across this code (simplified of course) in the project I have been assigned to.
Method Option 1
public myType getSomething(final int pTeamId) {
this.teamId = pTeamId;
final ClassABC classABC = new ClassABC(pTeamId);
...
return myType;
}
Notice how the input parameter pTeamId is being assigned to the private data member teamId in the first line of the method. Please note that there are getter and setter methods for this teamId data member (Which I have not bothered to include for simplicity's sake. Just know they are a standard getter/setter pair).
So I suppose I could write this method differently where I call the getter of the data member I just set instead of using the input parameter passed in directly as in Method Option 1:
Method Option 2
public myType getSomething(final int pTeamId) {
this.teamId = pTeamId;
final ClassABC classABC = new ClassABC(this.getTeamId());
...
return myType;
}
I realize this question may seem trivial and/or stupid to some, but I am encountering this situation frequently in a large code base I am modifying, so I am curious about which is the "correct" way to approach this, Method option 1 or Method option 2.
I came across this thread, but it targets JavaScript: speed of getter function vs direct access
My first inclination is to use Method Option 1, but I really do not have a good reason why, besides that "it looks faster...".
Can someone else provide a better reason(s)?
Specifically,
1) Is there is a proper/preferred convention/technique/practice in this scenario?
and
2) WHY is one option better than the other? Are they equal? Are there performance issues? etc.
Are there questions I am not asking? (or is this all an over-analysis)?
Any insight would be appreciated.
The getter could have logic in it like not returning null but an empty string instead.
same with the setter.
when you manipulate the variable directly you don't execute that logic.
this can also be a problem if someone overrides the getter and setter logic. (you can forbidd this by making them final) but this is not a common doing! (i would go one step further and call it an anti-pattern)
i would suggest always calling the getters/setters. and there is no real performance loss

Advanced Item Instance management trouble

I've been developing a massive Role Playing Game. The problem is that I'm having trouble engineering how will I manage the Item and Inventory system. Currently I have something similar to this:
public abstract class Item has 5 Nested classes which all are abstract and static that represent the types of Items. Every Nested class has an unique use(), delete() (Which finalizes the class instance) and sell()(triggers delete) void. They also have optional getter and setter methods, like the setAll() method which fills all necesary fields.
Default: Has base price, tradeability boolean, String name, etc... Very flexible
Weapon: Else than the things that the Default type has, it has integers for stat bonus on being equipped(used in the equip() and unequip() voids). Interacts with public class Hero.
Equipment: Similar to Weapon, just that it has an Enum field called 'EquipSlot' that determines where it is equipped.
Consumable: Similar to default, just that has a consume() void that enables the player to apply certain effects to an Hero when using it. Consuming usually means triggering the delete() void.
Special: Usually quest related items where the 'Tradeable' boolean is static, final and always false.
Now, the way that I make customized items is this.
First, I make a new class (Not abstract)
Then, I make it extend Item.ItemType
Then, I make a constructor which has the setAll(info) void inside.
Then, I can use this class in other classes.
It all looks like this:
package com.ep1ccraft.Classes.Items.Defaults;
import com.ep1ccraft.apis.Item.*;
public class ItemExample extends Item.Default {
public ItemExample() { // Constructor
this.setAll(lots of arguments here);
}
}
then I can do:
ItemExample something = new ItemExample();
And I have a perfect ItemExample with all the properties that I want, So, I can make various instances of it, and use amazing methods like 'getName()' and that kind of stuff.
The problems come to Naming the instances, as I do not know how to make an automated form that will give the instance a Different name from the other instance so they don't collide. Also, I want to implement an inventory system that uses slots as containers and can keep stacks (Stackable items only), also the main feature of it is that you can drag and drop them into other slots (For example, to reorganize or to move to another inventory instance like a bank, or to place in an hero's weapon or equipment slots, if it is allowed) and that you can click on them to display a screen that shows the name, description and possible actions of the Item (Which trigger the previously mentioned delete() and use() voids).
Thank you for reading all that! I know that maybe I'm asking for too much, but I'll appreciate any answers anyway!
So basically, you're asking for a unique identifier for your object. There are probably countless approaches to this, but the three different approaches that immediately come to mind are:
1: A UUID; something like:
java.util.UUID.randomUUID()
Pros: A very, very simple solution...
Cons: It does generate a large amount of bytes (16 + the object itself), taking memory / disk storage, which might be an issue in a MMO
2: A global running number; something like:
class ID {
private static volatile long id = 0;
public synchronized long nextId() {
return id++;
}
}
Pros: Again, a simple solution...
Cons: Even though this is a very simple class, it does contain "volatile" and "synchronized", which might be an issue for an MMO, especially if it is used heavily. Also, What happens after X years of running time, if you run out of numbers. A 64 bit long does require quite a lot of named objects to be created, it may not be an issue after all... you'll have to do the math yourself.
3: Named global running numbers; something like:
class NamedID {
private static volatile Map<String, Long> idMap = new HashMap<String, Long>();
public synchronized long nextId(String name) {
Long id = idMap.get(name);
if (id == null) {
id = 0;
} else {
id++;
}
idMap.put(name, id);
return id;
}
}
Pros: You get id's "localized" to whatever name you're using for it.
Cons: A bit more complex solution, and worse than "2" in terms of speed, since the synchronzation lasts longer.
Note: I couldn't figure out how to make this last suggestion faster; i thought of using a ConcurrentHashMap, but that won't work since it works on a lower level; i.e. it will not guarantee that two thread does not interfere with each other between the idMap.get and the idMap.put statements.

Categories

Resources