What is between C# and java Enum Constructor - java

I have a next code in C#:
public CryptoTimeInForce? TimeInForce ;
public void metod(SomeClass baseTrade){
this.TimeInForce = new CryptoTimeInForce?(baseTrade.TimeInForce);
}
CryptoTimeInForce is Enum
public enum CryptoTimeInForce : byte
{
///values
}
How I can create enum in java to provide the same logic like in C# code?
Enum in java cant be instantiated and i cant repeat same code in java.
Is there any alternatives?

In java, you get the '?' part for free, since java enums are objects, so they are always nullable.
In java, you cannot have an enum derive from byte, but that should not matter, it is just a performance optimization.
There are many other differences between java enums and C# enums, but absolutely none that would be a problem for what you are trying to do, from the code you have shown us.
Also, as DavidG comment says, it is entirely pointless to be instantiating an enum in C#, so the fact that you cannot instantiate an enum in java should be irrelevant. Enums are not meant to be instantiated, they are just constants.

Related

Is possible to create Java generics class depending on int value?

We can create a generic class in Java like this
public class MyClass<T> {
...
but, now that i'm translating a (very large) C++ code to Java, i need a class to be different from other depending on its size, like in this c++ code:
template<size_t size> class MyClass {
...
so every class is a different type, there static members are different, and members like "compare" can only be used with objects with the same size.
Is possible to do this in Java? if not, how would you handle this?
Sure, but it sucks.
You can model "counting' with a chain of recursive types. Inc<Inc<Inc<Integer>> could represent 3.
It is exceedingly awkward.
Java generics are not C++ templates. Java generics have a common base implementation and auto write some wrapping code to cast parameterized arguments to/from a common base in a thin wrapper.
C++ templates generate distinct types.
The design of C++ templates was to replace code generation and/or hand-rolled C code low level data structures. The goal was a template class could match or even exceed hand-written C versions (exceed because you can invest more engineering effort into the single template, and reuse it in 100s of spots).
Templates like std::function more closely approach Java generics. While the implementation is dissimilar, here it converts a myriad of types to one interface, hiding the casting from the end user. In C++ this technique is called type erasure, where std function "erases" all information about the stored callable except what it exposes. C++ type erasure does not require a common base class; Java does.
But because Java generics only supports one kind of type erssure, and C++ templates support not only more kinds of type erasure but also entitely different metaprogramming techniques that are alien to Java, replacing templates with Java generics is going to consistently run into problems. Only when the C++ use case happens to perfectly line up with the weaker Java generics does it work right.
(Note that, while weaker, Java generics make type erasure far easier, because they write a bunch of the casting code for you, and type check it. Weaker doesn't mean worse; it often means safer. But mechanically replacing a system with a weaker one often is doomed to failure.)
No, you can't use values as parameters instead of a generic type in Java. You should probably just take the size as a parameter in the constructor and implement safety checks taking the size into account.

What is the pros and cons between Enum and enum-based class implementation in Java?

I've recently come across an article discussing the use of an enum-based class implementation in C#, which is quite impressive. The second one here is in Java. However, my colleagues suggest me to use Enum instead.
Could anyone point out any pros and cons using each of them, and when to use it?
The Java article you quote is from 2001. Back then, Java didn't have enums, and the methods the author describes are what programmers used to do back then to work around Java's deficiency. Java 5 introduced enums in 2004 and now the older patterns are obsolete. So your colleagues are rght: you should use enums.
The Java standard enum implementation is already fully class based - you can define any methods, member variables, etc you like inside standard Java enums.
There is an excellent description of this with examples in the official enum documentation:
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
Additionally the EnumSet, EnumMap, etc collection classes are extremely powerful and efficient. EnumSet has similar performance to using raw bitfields! You only get access to those classes if you use a proper enum though.
In Java, Enum types act as a class that is declared with their unique name. It is pretty much like the any other class that is designed to create constant values. Recently, I also came across to an info that before the declaration of Enums in Java, an enum like class was created. Just like the article that was suggested on this question, it seems that previous to JVM 1.5, class based enums were widely used.
You can check this source: http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html
I think it is a very good explanation on Java Enums and Why they are created. The article claims 3 advantages for Enum:
1)Type Safety.
2)Unless the class was worked thoroughly, the Enum class was prone to printing problems. When coder wanted a string result to be returned, an primitive value was returned. To my experience, with some additions to the class, this is avoided. But question is, is it convenient for the coder.
3)Again, access was based on an instance of the class. Thus, coder cannot access to the Enum option directly. Coder must use the class name.
As a result: for convenience and code readability issues, Enums are a good choice. Plus, Enum Structure is similar to an individual classes that are nested within a carrier class. If coder wants to enhance the Enum Design and create their own style, they can turn back to the old manually coded class based system.
The major difference is that Java's enums are more simple, one may not switch on the C# enum-based class implementation and enum-based class is more of a class than of an enumerated data type, i.e. it can be extended. Whereas enum can't be derived from another class and can not be extended.
Java alternative for C# enum-based class could be like:
public abstract static class CreditCard {
enum CreditCardType{
AMERICAN_EXPRESS, MASTER, VISA, DISCOVER;
}
CreditCardType type;
public abstract void operation1();
public abstract void operation2();
}
HI I will suggest to use enum if you know how to use it.
because their are many reasons some of them are
uses less memory
having some constant value
less process time
easy to understand
reuseability
easy to debug
like that it is having many advantage but other-hand it is having many disadvantage also like
limited use means we are having some limitation by using enum

Are functions only in non-object-oriented languages? [duplicate]

This question already has answers here:
What's the difference between a method and a function?
(41 answers)
Closed 9 years ago.
I was asked to answer this question:
Where should I put the Javadoc specific comment notation of /** and */
if I want to tell the user specifics about a certain instance variable
or method?
I answered with:
Above the function declaration.
The answer was rejected and this was the reason:
Functions are in non-object-oriented languages. Method is the proper name.
Is this true?
Are functions found only in non-object-oriented languages?
No. There are object-oriented languages that have functions. C#, for example, is an object-oriented language but it has anonymous functions.
What are the named procedures which are members of a type typically called in object-oriented languages like Java or C#?
Typically they are properly called methods, though this differs from language to language. In Java or C# I would say "method".
In Visual Basic, for example, the distiction is made between functions and subroutines on the basis of whether or not they return a value, not on the basis of whether they are associated with a type container.
JavaScript, an object-oriented language which uses prototype inheritance rather than class inheritance, typically refers to all of the above as "functions".
Do people frequently refer to methods as functions when speaking casually about Java or C#?
Yes. Were I writing documentation or a book or a scholarly article then I would be careful to make the distinction. In commonplace parlance though everyone reasonably conversant with the art of computer programming would understand "function" and "method" to be roughly synonyms. I would not have rejected your answer.
Any answer which limits this to a specific language is inherently flawed. In addition you must also deal effectively with static methods and subroutines.
Computer science began with the term 'subroutine'. Small sections of repeatable code which could be executed arbitrarily to perform a common action. Examples are found in early programming languages such as BASIC.
Functions were the evolution of subroutines. They take arguments and may or may not return a value. They take some concepts from maths - input, translated to a given output.
With objects we need to be able to call actions on objects and we do this be exposing methods. Like functions they take arguments and may or may not return a value.
Static methods are designed to act on all possible objects of a class.
The problem is that, pure object-orientated programming leaves no scope for the definition of functions (or indeed subroutines). And languages that evolve to become object orientated often retain syntax from functions to implement methods.
In Java we resort to using 'Utility' classes to provide functions as public static methods. The Math class in JavaScript is another example of this.
In PHP we tolerate the use of the word function to define methods.
In C++ we see both functions and methods, neither demarcated. Indeed, C++ makes no reference to methods, calling them member functions.
A function is not bound to a class.
A function is something like doStuff();.
A method is like someThing.doStuff(); or SomeClass.doStuff();.
In Java, there is no such thing as a function. They are all methods. i.e.
class Test {
public static void doSomething() {...}
public void otherThing() {...}
public static void main(String[] args) {
doSomething(); //implied Test.doSomething();
}
public Test() {
otherThing(); //implied this.otherThing();
}
}

Can the methods in an Enum type change the state of the instances of an Enum?

If Enums are an answer for getting rid of compile time constants , why did the language designers provide facility to let arbitrary methods and fields and implement arbitrary interfaces on Enums ? Those methods can never change the state of the Enum instances or can they ? If they are allowed to change the state , then the invariant of an Enum type ie some type that exports a few constants will break IMHO.
Java enums are really just classes with some special treatment by the compiler and runtime. So yes, method calls on an enum instance can certainly change its state. I'm not sure what you mean with "then the invariant of an Enum type ie some type that exports a few constants will break".
Who says enums can only be a bunch of constants? The essence of an enum type is that you have a predefined fixed number of instances which you can refer to by name - and Java enums implement that. But why would a language not be allowed to have enums that are more powerful than that?
If you don't want the extra power, nobody forces you to use it. You can have Java enums without fields or methods, and they'll behave pretty much exactly like C enums.
Enums are compile-time constants, but their members aren't. It's usually not a good idea to change enum members at runtime, but it is possible. For this reason, you can't use an enum's members where compile-time constants are called for (e.g. in annotation parameters).
Hardly anything in Java is really a constant when you go try hard to mess things up. E.g. a String constant contains a char array. Arrays are not immutable. Here's an example of the mess you can make using inlined String constants:
public static void main(final String[] args) throws Exception {
final Field valueField = String.class.getDeclaredField("value");
valueField.setAccessible(true);
System.arraycopy("frog".toCharArray(), 0,
(char[]) valueField.get(Boolean.TRUE.toString()), 0, 4);
System.out.println(Boolean.parseBoolean("frog")); // true
System.out.println(Boolean.parseBoolean("true")); // false
}
So, Java constants in most cases are just constants as long as your application is well-behaved.
why did the language designers provide facility to let arbitrary methods and fields and implement arbitrary interfaces on Enums
Reasons are to allow replacing switch-statements with polymorphism and generally make programs more Object Oriented by allowing to define methods on the data.
Search for "type-safe enum pattern". Java Enums are an implementation of this design pattern on language level.

Enum in Java. Advantages?

What are some advantages of making enum in Java similar to a class, rather than just a collection of constants as in C/C++?
You get free compile time checking of valid values. Using
public static int OPTION_ONE = 0;
public static int OPTION_TWO = 1;
does not ensure
void selectOption(int option) {
...
}
will only accept 0 or 1 as a parameter value. Using an enum, that is guaranteed. Moreover, this leads to more self documenting code, because you can use code completion to see all enum values.
Type safety is one reason.
Another, that I find more important, is that you can attach metadata to enum values in Java. For example, you could use an enum to define the set of legal operations for a webservice, and then attach metadata for the type of request and data class:
AddItem(HttpMethod.POST, ProductEntry.class),
Java 5 enums originated from a typesafe enum pattern from Joshua Bloch's Effective Java (the first edition) to avoid the pitfalls of enums in C/C++/C# (which are simply thinly-veiled int constants) and the use in Java of final static int constants.
Primarily int constants and int enums aren't typesafe. You can pass in any int value. In C/C++ you can do this:
enum A { one, two, three };
enum B { beef, chicken, pork } b = beef;
void func(A a) { ... }
func((A)b);
Unfortunately the typesafe enum pattern from Effective Java had a lot of boilerplate, not all of it obvious. The most notable is you had to override the private method readResolve to stop Java creating new instances on deserialization, which would break simple reference checking (ie using the == operator instead of equals()).
So Java 5 enums offer these advantages over ints:
Type safety;
Java 5 enums can have behaviour and implement interfaces;
Java 5 enums have some extremely lightweight data structures like EnumSet and EnumMap.
Java 5 enums over these advantages over just using classes:
Less error-prone boilerplate (private constructor, readResolve() etc);
Semantic correctness. You see something is an enum and you know it's just representing a value. You see a class and you're not sure. Maybe there's a static factory method somewhere, etc. Java 5 enums much more clearly indicate intent.
Enums are already a class in Java.
If you're asking why this is better, I'd say that better type safety and the ability to add other attributes besides a mere ordinal value would come to mind.
In addition to better type safety, you can also define custom behavior in your enums (refer to Effective Java for some good examples).
You can use enums to effectively implement Singletons ^^:
public enum Elvis {
INSTANCE
}
Making enum a reference type that can contain fixed set of constants has led to efficient Map implementation like EnumMap and Set implementation like EnumSet (JDK classes).
From javadoc of EnumMap :
A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.
EnumMap combines richness and type safety of Map with the speed of an array (Effective Java).
Enums are a type in itself - you cannot use an enum that does not exist, or put in some other similar looking constant. and also, you can enumerate them, so that code can be more concise.
using static constants could potentially cause maintenence nightmares - especially if they area spread out.
The only real advantage is that it can be used in a switch statement. All the other stuff an enum is capable of can just be done with plain vanilla class with a private constructor whose instances in turn are declared as public static final fields of the class in question (the typesafe pattern). The other advantage of enum is obviously that it makes the code less verbose than you would do with a plain vanilla class.
But if I'm not mistaken, in C++ (or was it C#?) you can use a String in a switch statement. So that advantage of enums in Java is negligible as opposed to C++. However, same thing was proposed for Java 7, not sure if it will make it.
Benefits of Using Enumerations:
An object can be created to work in the same manner as an enumeration. In fact,
enumerations were not even included in the Java language until version 5.0. However,
enumerations make code more readable and provide less room for programmer error.
OCA Java SE 7 Programmer I Study Guide

Categories

Resources