I'm fairly new to Java and I'm trying to use the + character as part of an enum type, but the compiler is complaining about the syntax because I believe it sees it as an operator.
I'd like to do the following:
enum mediaType{
FACEBOOK,GOOGLE+,TWITTER;
}
Any ideas?
Thanks!
Yes, the compiler will treat + as an operator. You can however choose a different name there:
enum mediaType{
FACEBOOK,
GOOGLE_PLUS,
TWITTER;
}
And if you want to use the value GOOGLE+ only, then have a field of type String, storing the value, and also a parameterized constructor.
P.S: As per proper naming convention, the enum name should be MediaType.
You can't use arithmetic symbols in identifiers. You need to find something you can use like GOOGLE_PLUS
Maybe reading the official Java tutorial's section on Naming Conventions will help you: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
You could at least define a private String myName = "Google+"; inside the enum, and define a method that a UI can use to get the value you want rather than just displaying the enum's variable itself.
public String myName() {
return myName;
}
Many people believe that you are limited to ASCII in Java just like C and C++.
Actually you have the full Unicode character set.
This is perfectly good Java:
enum Plus {
Google,
GooglePlus,
Googleᚋ,
Googleᐩ;
};
Not quite a + (which you cannot have in an enum because it will be confused with the + operator) but it will still carry the impression of a plus.
It seems you can use the Ogham character called muin which looks a bit like a plus character. Alternatively it seems the Canadian syllabics final plus is also acceptable alhough a number of the other possibilities seem not to be acceptable.
Related
I am aware there are similar questions, and I have read the answers, but maybe I'm just not quite grasping the full difference of its use, even though I understand their difference when for example, initializing a String. Example:
String[] favorite = {"dog", "cat", "alien"};
vs
enum favorite = {dog, cat, alien}
Or maybe the use of either in the above case is similar, but their difference can be grasped better in another example? Is it that enum can clearly store more properties for a variable when creating the class?
The big advantage of enum is that the compiler checks for typos (type safety). For instance, if you assign the value "dag" to a string, the compiler does not complain. But, you cannot assign the value favorite.dag to a variable (of type favorit). Also, enum makes the code more readable and it is faster (comparison, for instance).
Just like #AhmadWabbi said, it's mostly type safety.
With enums you also have the ability to write methods corresponding to the enum.
For instance:
public enum Favorite = {
dog("woof"),
cat("meow"),
alien("zoink")
private String sound;
Favorite(String sound) {
this.sound = sound;
}
public String makeSound() {
return sound;
}
}
Which then let you call the method on a known enum (Favorite.dog.makeSound()) or if the enum is a parameter to another method.
The biggest advantage is that an enum is type-safe. An enum value can only take on one of the defined values (or null). (Note that an enum in Java is not like an enum in C++ or C#, where it is more like an alias for an int).
If you use a type like String or int, you can assign to that any value that fits in a String or int, even if it's not one of the limited set of values that you want it to contain.
It also makes programs easier to read, because when for example a method takes an enum type as a parameter, you immediately know what it means, and what values are valid - if it would, for example, take a String, you don't automatically know which strings are valid inputs and which are not.
There is no need to be too sophisticated with a program.
If you have three strings use the string array. If you have three distinct entities which differ by something else in addition to their names, use enum (on which you, evidently, will then be operating somehow).
Enums are easy to add new functionality to your code. Strings have their limits, you can decide yourself if you need all the benefits of enums or string will do for the job.
For example:
public enum favourite {
dog, cat, cow;
public boolean barking(){
switch(this){
case dog:
return true;
case cat:
case cow:
return false;
}
throw new AssertionError();
}
}
Enum sort of create a namespace . Thus two constants with same name can belong to different enums. Of course , you can emulate it with ArrayList but its not intuitive , because its supposed to acts as a container rather than a logical namespace holding constants.
You can compare it old style enums from C++ , where two enum declarations holding a same named constant shows a error . With new style class enums in c++ adds sort of namespace to it , which was not possible earlier.
And yes
Enums in Java already have a name-spacing feature.
By the way , Enum and ArrayList both have different purpose.
The biggest advantage of enums is that they are type-safe: a variable of an enum type can only hold values defined in that enum. By the way, in some circumstances this can be a big disadvantage, a show-stopper even: if the possible values are not known at compile time (for example, because you need to fetch them from a database at run-time) you cannot use enums.
Although I do not see a clear advantage of it (and if I don't see a clear advantage I would always use the established coding practice, which is using an enum), you can certainly use strings as a kind of enums. Performance will probably be a bit worse because of the string comparisons, but in most cases unnoticeably so.
However, I would strictly advice against your array example, for the following reasons:
Arrays are mutable. If your project is large enough, someone will eventually write favorites[0] = "beer"; and thus cause mysterious bugs in unrelated parts of the code.
Using an array has no advantage in readability. The meaning String myFavorite = favorites[1]; is completely opaque, whereas String myFavorite = "cat"; or Favorite myFavorite = Favorite.CAT; are immediately clear.
String literals can be used in switch statements, but not expressions like favorites[2]. So switch (myFavorite) { case favorites[2]: ... } is not legal Java (whereas switch (myFavorite) { case "alien": ... } is).
If you really want to use Strings as enums, then define String constants:
public static final String FAV_DOG = "dog";
public static final String FAV_CAT = "cat";
public static final String FAV_ALIEN = "alien";
I'm new to Java and I couldn't find an answer to it anywhere because i don't even know how to search for it.
I want to define how 2 objects can be added together, so you get a new one like for example you can add String "a" and String "b" to get "ab".
I know this can be done in python by doing self.__add__(self, other).
How can you do this in Java?
The thing you are looking for is called operator overloading. It exists in some languages, however in Java it does not.
The best thing you can do is to define a method add() inside the class and then use it like this:
object1.add(object2);
I know it looks nicer with a + between them, but that would make compiling more complex.
With the exception of java.lang.String being treated as a special case1, Java does not allow you to define the behaviour of + for arbitrary types, or indeed any other operator, as you can in some languages such as C++ or Scala. In other words, Java does not support operator overloading.
Your best bet is to build functions like add &c. Appeal to precedent here: see how the Java guys have done it with BigInteger, for example. Sadly there is no way of defining the precedence of your functions, so you have to use very many parentheses to tell the compiler how you want an expression to be evaluated. It's for this reason that I don't use Java for any serious mathematical applications as the implementation of even a simple equation quickly becomes an unreadable mess2.
1 Which in some ways does more harm than good: e.g. consider 1 + 2 + "Hello" + 3 + 4. This compile time constant expression is a string type with the value 3Hello34.
2 Note that C++ was used to model the gravitational lensing effects of the wormhole in the movie "Interstellar". I challenge anyone to do that in a language that does not support operator overloading! See https://arxiv.org/pdf/1502.03808v1.pdf
Java does not allow you to override operators. String is a special case that does allow this functionality.
What you can do is add an add function like so:
public YourObject add(YourObject yourObject){
return new YourObject(this.propertyToAdd + yourObject.propertyToAdd);
}
I read about the naming of Java variables. It says that Java variables cannot start with any numbers and special characters except for $ and _.
Some valid examples:
int count;
int _count;
int $count;
And some invalid examples:
int %count;
int 4count;
int #count;
Do the same rules apply to method names?
Yes, method names and variable names are what's called "identifiers". Identifiers all share the same rules regarding accepted characters. Take a look at §3.8 from the Java Language Specification to find out exactly what an identifier may contain, and §6.2 for an explanation about how identifiers are used.
You might be surprised when having unusual characters for method, such as:
public void mój_brzuch_zacznie_burczeć()
and it works pretty nice. Take a look at this blog to see more fancy examples.
From the Java Tutorial:
"Although a method name can be any legal identifier, code conventions restrict method names."
http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to have properties and methods that share the same name, but I don't think that comes up much.
The only big benefit I can come up with is readability. Sometimes you might want to know whether something is a method or a property while you're looking at code, but I'm having trouble coming up with specific examples when that would be really helpful. But I am a n00b, so I probably just haven't encountered such a situation yet. I'd appreciate examples of such a situation.
Also, are there other languages where the difference isn't explicit?
Anyways, if you could answer, it will help me be less annoyed every time I make this mistake ^-^.
UPDATE:
Thanks everyone for the awesome answers so far! I only have about a week's worth of js, and 1 day of python, so I had no idea you could reference functions without calling them. That's awesome. I have a little more experience with java, so that's where I was mostly coming from... can anyone come up with an equally compelling argument for that to be the case in java, where you can't reference functions? Aside from it being a very explicit language, with all the benefits that entails :).
All modern languages require this because referencing a function and calling a function are separate actions.
For example,
def func():
print "hello"
return 10
a = func
a()
Clearly, a = func and a = func() have very different meanings.
Ruby--the most likely language you're thinking of in contrast--doesn't require the parentheses; it can do this because it doesn't support taking references to functions.
In languages like Python and JavaScript, functions are first–class objects. This means that you can pass functions around, just like you can pass around any other value. The parentheses after the function name (the () in myfunc()) actually constitute an operator, just like + or *. Instead of meaning "add this number to another number" (in the case of +), () means "execute the preceding function". This is necessary because it is possible to use a function without executing it. For example, you may wish to compare it to another function using ==, or you may wish to pass it into another function, such as in this JavaScript example:
function alertSomething(message) {
alert(message);
}
function myOtherFunction(someFunction, someArg) {
someFunction(someArg);
}
// here we are using the alertSomething function without calling it directly
myOtherFunction(alertSomething, "Hello, araneae!");
In short: it is important to be able to refer to a function without calling it — this is why the distinction is necessary.
At least in JS, its because you can pass functions around.
var func = new Function();
you can then so something like
var f = func
f()
so 'f' and 'func' are references to the function, and f() or func() is the invocation of the function.
which is not the same as
var val = f();
which assigns the result of the invocation to a var.
For Java, you cannot pass functions around, at least like you can in JS, so there is no reason the language needs to require a () to invoke a method. But it is what it is.
I can't speak at all for python.
But the main point is different languages might have reasons why syntax may be necessary, and sometimes syntax is just syntax.
I think you answered it yourself:
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
Consider the following:
if (colorOfTheSky == 'blue')
vs:
if (colorOfTheSky() == 'blue')
We can tell just by looking that the first checks for a variable called colorOfTheSky, and we want to know if its value is blue. In the second, we know that colorOfTheSky() calls a function (method) and we want to know if its return value is blue.
If we didn't have this distinction it would be extremely ambiguous in situations like this.
To answer your last question, I don't know of any languages that don't have this distinction.
Also, you probably have a design problem if you can't tell the difference between your methods and your properties; as another answer points out, methods and properties have different roles to play. Furthermore it is good practice for your method names to be actions, e.g. getPageTitle, getUserId, etc., and for your properties to be nouns, e.g., pageTitle, userId. These should be easily decipherable in your code for both you and anyone who comes along later and reads your code.
If you're having troubles, distinguishing between your properties and methods, you're probably not naming them very well.
In general, your methods should have a verb in them: i.e. write, print, echo, open, close, get, set, and property names should be nouns or adjectives: name, color, filled, loaded.
It's very important to use meaningful method and property names, without it, you'll find that you'll have difficulty reading your own code.
In Java, I can think of two reasons why the () is required:
1) Java had a specific design goal to have a "C/C++ like" syntax, to make it easy for C and C++ programmers to learn the language. Both C and C++ require the parentheses.
2) The Java syntax specifically requires the parentheses to disambiguate a reference to an attribute or local from a call to a method. This is because method names and attribute / local names are declared in different namespaces. So the following is legal Java:
public class SomeClass {
private int name;
private int name() { ... }
...
int norm = name; // this one
}
If the () was not required for a method call, the compiler would not be able to tell if the labeled statement ("this one") was assigning the value of the name attribute or the result of calling the name() method.
The difference isn't always explicit in VBA. This is a call to a Sub (i.e. a method with no return value) which takes no parameters (all examples are from Excel):
Worksheets("Sheet1").UsedRange.Columns.AutoFit
whereas this is accessing an attribute then passing it as a parameter:
MsgBox Application.Creator
As in the previous example, parentheses are also optional around parameters if there is no need to deal with the return value:
Application.Goto Worksheets("Sheet2").Range("A1")
but are needed if the return value is used:
iRows = Len("hello world")
Because referencing and calling a method are two different things. Consider X.method being the method of class X and x being an instance of X, so x.method == 'blue' would'nt ever be able to be true because methods are not strings.
You can try this: print a method of an object:
>>> class X(object):
... def a(self):
... print 'a'
...
>>> x=X()
>>> print x.a
<bound method X.a of <__main__.X object at 0x0235A910>>
Typically properties are accessors, and methods perform some sort of action. Going on this assumption, it's cheap to use a property, expensive to use a method.
Foo.Bar, for example, would indicate to me that it would return a value, like a string, without lots of overhead.
Foo.Bar() (or more likely, Foo.GetBar()), on the other hand, implies needing to retrieve the value for "Bar", perhaps from a database.
Properties and methods have different purposes and different implications, so they should be differentiated in code as well.
By the way, in all languages I know of the difference in syntax is explicit, but behind the scenes properties are often treated as simply special method calls.
I'm looking at some Java code that are maintained by other parts of the company, incidentally some former C and C++ devs. One thing that is ubiquitous is the use of static integer constants, such as
class Engine {
private static int ENGINE_IDLE = 0;
private static int ENGINE_COLLECTING = 1;
...
}
Besides a lacking 'final' qualifier, I'm a bit bothered by this kind of code. What I would have liked to see, being trained primarily in Java from school, would be something more like
class Engine {
private enum State { Idle, Collecting };
...
}
However, the arguments fail me. Why, if at all, is the latter better than the former?
Why, if at all, is the latter better
than the former?
It is much better because it gives you type safety and is self-documenting. With integer constants, you have to look at the API doc to find out what values are valid, and nothing prevents you from using invalid values (or, perhaps worse, integer constants that are completely unrelated). With Enums, the method signature tells you directly what values are valid (IDE autocompletion will work) and it's impossible to use an invalid value.
The "integer constant enums" pattern is unfortunately very common, even in the Java Standard API (and widely copied from there) because Java did not have Enums prior to Java 5.
An excerpt from the official docs, http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html:
This pattern has many problems, such as:
Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.
And this just about covers it. A one word argument would be that enums are just more readable and informative.
One more thing is that enums, like classes. can have fields and methods. This gives you the option to encompass some additional information about each type of state in the enum itself.
Because enums provide type safety. In the first case, you can pass any integer and if you use enum you are restricted to Idle and Collecting.
FYI : http://www.javapractices.com/topic/TopicAction.do?Id=1.
By using an int to refer to a constant, you're not forcing someone to actually use that constant. So, for example, you might have a method which takes an engine state, to which someone might happy invoke with:
engine.updateState(1);
Using an enum forces the user to stick with the explanatory label, so it is more legible.
There is one situation when static constance is preferred (rather that the code is legacy with tonne of dependency) and that is when the member of that value are not/may later not be finite.
Imagine if you may later add new state like Collected. The only way to do it with enum is to edit the original code which can be problem if the modification is done when there are already a lot of code manipulating it. Other than this, I personally see no reason why enum is not used.
Just my thought.
Readabiliy - When you use enums and do State.Idle, the reader immediately knows that you are talking about an idle state. Compare this with 4 or 5.
Type Safety - When use enum, even by mistake the user cannot pass a wrong value, as compiler will force him to use one of the pre-declared values in the enum. In case of simple integers, he could even pass -3274.
Maintainability - If you wanted to add a new state Waiting, then it would be very easy to add new state by adding a constant Waiting in your enum State without casuing any confusion.
The reasons from the spec, which Lajcik quotes, are explained in more detail in Josh Bloch's Effective Java, Item 30. If you have access to that book, I'd recommend perusing it. Java Enums are full-fledged classes which is why you get compile-time type safety. You can also give them behavior, giving you better encapsulation.
The former is common in code that started pre-1.5. Actually, another common idiom was to define your constants in an interface, because they didn't have any code.
Enums also give you a great deal of flexibility. Since Enums are essentially classes, you can augment them with useful methods (such as providing an internationalized resource string corresponding to a certain value in the enumeration, converting back and forth between instances of the enum type and other representations that may be required, etc.)