Is there a way to override the assignment operator in Java ?
For example, I can always do something like:
AJSDate startDate = new AJSDate("20090811");
but I would rather have it as:
AJSDate startDate = "20090811";
Is there a way to override the assignment operator in Java ?
For example, I can always do something like:
AJSDate startDate = new AJSDate("20090811");
but I would rather have it as:
AJSDate startDate = "20090811";
No. Java doesn't support the overloading of operators.
You can't even extend String to do something like this:
class AJSDate extends String {
}
public class HelloWorld {
public static void main(String []args){
AJSDate ajs = "This is a test";
System.out.println(ajs);
}
}
You would get the following compile-time errors:
error: cannot inherit from final String
(for trying to extend String - String is a final class which means it can't be extended)
error: incompatible types
(for AJSDate ajs = "This is a test";
- the operands on either side of the =
operator aren't type-compatible.)
If you really want to write a program that allows operator overloading, use another language such as C++, Scala or Ruby.
A more minor point, but if you would like to create an object with the functionality of another object (i.e., that extends another object) then stylistically, you probably want to end the name of its class with the name of its parent class. E.g. if it extends class Foo, call it AJSDateFoo.
Not in Java itself. Unfortunately for those cases where operator overloading is useful.
However, as operator overloading is basically syntactic sugar the JVM doesn't forbid it. Other JVM languages e.g. Scala has some operator overloading support.