Implementation of Enum - java

I am trying to do a bit of reverse engineering on enum.
public class test {
public static void main(String[] args) {
num number=num.one;
System.out.println(number); //outputs result as one
}
}
enum num{
one;
}
Now how do I implement the same without using enum.
public class Lab24a {
public static void main(String[] args) {
num1 num= num1.one;
System.out.println(num);
}
}
class num1{
public static final num1 one= new num1();
private num1(){
}
public String toString(){
return //how to implement the two string totally lost here.
}
}
I was able to write a code until this, but I am not able to printout the value, please give me your suggestions or hints. I even tried looking at the following links.
Confusion with Enum type
enum implementation inside interface - Java

Why not use an enum? IMO Java is missing some key features, but one of the things it does right it is the way it uses enums.
If you really want to avoid an enum, you could do this:
class num1{
public static final num1 one= new num1("one");
private String name;
private num1(String name) {
this.name = name;
}
#Override //Be sure to add the override annotation here!
public String toString(){
return name;
}
}

Related

Is there a way to Compare Multiple Enum Types with each other in Java [duplicate]

This question already has answers here:
Java - get the current class name?
(12 answers)
Closed 3 months ago.
Lets take this for Example:
public class Vehicle {
public enum Car {
CAR1,
CAR2,
CAR3,
CAR4,
}
public enum BIKE {
BIKE1,
BIKE2,
BIKE3
}
}
public class Main {
public static void main(String args[]) {
Vehicle.Car value1 = Vehicle.Car.CAR1;
Vehicle.Bike value2 = Vehicle.Bike.BIKE1;
print(evaluateType(value1));
// Expected Output: Car
print(evaluateType(value2));
// Expected Output: Bike
}
}
Now the use case here is, We have to write the function evaluateType. I was wondering if there is a way to know the type of Enum we are using, if it is of type Bike or Car.
Given the fact the enums are stored as Int in memory, this doesn't seems like it can be done. But looking forward to any suggestion on how this type of situations could be handled.
Thank you.
Not sure if that is what you want but:
public class BaseClass {
public enum PropertyTypeString {
STRING1,
STRING2,
STRING3,
STRING4,
STRING5,
}
public enum PropertyTypeInt {
INT1,
INT2,
INT3
}
}
public class Main {
public static void main(String args[]) {
BaseClass.PropertyTypeString value = BaseClass.PropertyTypeString.STRING1;
BaseClass.PropertyTypeInt value_2 = BaseClass.PropertyTypeInt.INT1;
evaluateType(value);
evaluateType(value_2);
}
public static void evaluateType(Enum value)
{
System.out.println(value.getClass());
}
}
You can attach values to enum, you don't need to stick with basic enum :
public enum Element {
H("Hydrogen"),
HE("Helium"),
// ...
NE("Neon");
public final String label;
private Element(String label) {
this.label = label;
}
}
source : https://www.baeldung.com/java-enum-values

Java visible interface that can not be implemented

I'm working on making a programming language that compiles to JVM bytecode, and it highly relies on interfaces as types. I need some way to make an interface private, but have other code still be able to access it, but not make something that implements it.
I was thinking about using abstract classes with a private constructor, so only the classes in the same file would be able to access it. The only problem is that it is impossible to extend multiple abstract classes at once. For example, the structure of a simple compiled program would be this:
// -> Main.java
public class Main {
public static MyInteger getMyInteger() {
return new MyIntegerImpl(10);
}
public static void main(String[] args) {}
private interface MyInteger {
public int getValue();
}
private static class MyIntegerImpl implements MyInteger {
private final int value;
public int getValue() {
return value;
}
public MyIntegerImpl(int value) {
this.value = value;
}
}
}
And another file, in which there is a problem:
// -> OtherFile.java
public class OtherFile {
public static void main(String[] args) {
Main.MyInteger myInteger = Main.getMyInteger(); //Error: The type Main.MyInteger is not visible.
System.out.println(myInteger.getValue());
}
//I do not want this to be allowed
public static class sneakyInteger implements Main.MyInteger { //Error(Which is good)
public int getValue() {
System.out.println("Person accessed value");
return 10;
}
}
}
The reason why I want to do this is so one person can not mess up any other person's code by providing their own implementations of things that should be only implemented by that other person.
Any help would be much appreciated.
I'm pretty sure that you should think again about what you are trying to do and change approach, but the answer for your question is to add to the interface some empty void method that is getting the parameter of the inner private class specific for the wrapper class
public class Test {
private class InnerPrivateClass {
private InnerPrivateClass() {}
}
public interface MyInteger {
int getValue();
void accept(InnerPrivateClass c);
}
private class MyIntegerImpl implements MyInteger {
#Override
public int getValue() {
return 0;
}
#Override
public void accept(InnerPrivateClass c) {}
}
}
However, as I said, I don't like this and for me it means that your idea is broken

Pass class constants as parameter in java

I want to pass a class constants to function as parameter code is
public class XConstants {
public static final String DATA= "DATA";
public static final String SET = "Node";
}
public static void main(String[] args) {
foo(XConstants.DATA);
}
public static void foo(XConstants d){
System.out.println(d);
}
Here in the main method i am passing the XConstants.DATA to foo function but it gives me compile error of type miss match which is obvious because XConstants.DATA is type of String.
Similarly if i use enum and pass enum value to function parameter it will works perfectly fine. code is
enum Color{RED,BLUE}
public static void main(String[] args) {
bar(Color.RED);
}
public static void bar(Color d){
System.out.println(d);
}
Here enum is value is simply passing as a parameter.
I want to know that how should i change my code of XConstants so that it will work same as enum mentioned in the code are working (I know both are different things).
please note that i do not want to change the method signature like
public static void main(String[] args) {
foo(XConstants.DATA);
}
public static void foo(String d){
System.out.println(d);
}
It will work fine in this case because in this case type mis match conflict resolves.
To be short i want to know how should i change my XContants code ,r which design pattern should i use to achieving this working fine as it is working in the case of enum.
Any help will be greatly appreciated
enum Color{RED,BLUE} is similar to
class Color{
public final static Color RED = new Color("RED");
public final static Color BLUE = new Color("BLUE");
private String name;
private Color(String name){
this.name = name;
}
public String toString(){
return name;
}
//...rest of code like `values()`, and `ordinal()` methods
}
So if method is expecting Color it is possible to pass Color.RED, because RED it is instance of type Color.
Now depending on your requirements you can try to adapt your XConstants to this pattern.
I'm not sure why would you would want to do this when you already know that enums fit your purpose perfectly. If you're just curious to know if it's possible to achieve this with classes, read on.
Enums in many ways behave like classes. I think you'll already know that they can have fields, constructors and methods as well. But, the most important thing that concerns what interests you at the moment is that an enum constant's type is that of the enum itself.
So, to achieve this enum like behaviour you just have to model your class that way.
public class XConstants {
private String name;
public XConstants(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
public static final XConstants DATA = new XConstants("DATA");
public static final XConstants SET = new XConstants("Node");
public static void main(String[] args) {
foo(XConstants.DATA);
foo(XConstants.SET);
}
public static void foo(XConstants d) {
System.out.println(d);
}
}
Output:
DATA
Node

How does a static method use a comparator?

I have a static method which needs to invoke the SportsMenComparator. But this, as we all know is not allowed. How does a static function use a comparator subclass ? Although I have workarounds, I am looking for best practices for this particular problem.
final class SportsMan {
private final String name;
private final int rank;
private final String sport;
public SportsMan (String name, int rank, String sport) {
this.name = name;
this.rank = rank;
this.sport = sport;
}
public String getName() {
return name;
}
public int getRank() {
return rank;
}
public String getSport() {
return sport;
}
}
final class Sport {
private final String sport;
private final int numberOfPlayers;
public Sport(String sport, int numberOfPlayers) {
this.sport = sport;
this.numberOfPlayers = numberOfPlayers;
}
public String getSport() {
return sport;
}
public int getNumberOfPlayers() {
return numberOfPlayers;
}
}
public final class Joins {
private Joins () {}
public class SportsMenComparator implements Comparator<SportsMan> {
#Override
public int compare(SportsMan s1, SportsMan s2) {
return s1.getSport().compareTo(s2.getSport());
}
}
public static void innerJoinSort(List<SportsMan> sportsMans, List<Sport> sportList) {
Collections.sort(sportsMans, new SportsMenComparator());
}
}
Eclipse results in the following message: No enclosing instance of type Joins is accessible where Joins is name of the enclosing class.
But this, as we all know is not allowed. How does a static function use a comparator subclass ?
You cannot use a non static reference,still you are allowed to create a new object and use it. So since you are creating a new SportsMenComparator object and passing, no issues.
For example:
public static void main(String[] args) {
List<String> s =new ArrayList<String>();
s.add(""); // allowed
}
But
List<String> s =new ArrayList<String>();
public static void main(String[] args) {
System.out.println();
s.add(""); // Error: Cannot make a static reference to the non-static field s
}
Edit:
Since you defined the comparator class inside the Joins , you need the Joins object to access the comparation inside it
Collections.sort(sportsMans, new Joins().new SportsMenComparator());
For using a Comparator, there is no difference between using it from a static- or non-static method. In either case an instance of the Comparator has to be used.
The Garbage Collector of modern JVMs is very efficient at handling short-lived objects. Therefore the penalty to be paid for using a fresh instance (via new) every time is usually no issue. However, if you don't want to use a fresh instance every time, I think the best option would be to add a static field to your SportsMenComparator, containing a singleton instance of the comparator:
public class SportsMenComparator implements Comparator<SportsMan> {
public static final SportsMenComparator instance=new SportsMenComparator();
#Override
public int compare(SportsMan s1, SportsMan s2) {
return s1.getSport().compareTo(s2.getSport());
}
}
public static void innerJoinSort(List<SportsMan> sportsMans, List<Sport> sportList) {
Collections.sort(sportsMans, SportsMenComparator.instance);
}
The problem is that you try to access an instance element (in this case it is a class, indeed the same as with a filed or method) within a static method, which is not associated with an instance. SURESH ATTA's answer is right, but you can also make your SportsMenComparator class static and it will work. I do not sse any reason to associate your comparator with an instance of the Joins class.
One can use something like this---
public static boolean someMethod(MyObject obj1, MyObject obj2){
return obj1.compare(obj2);
}
Why you cant include parameter to the function.
public static void innerJoinSort(List<SportsMan> sportsMans, List<Sport> sportList, Comparator comparator) {
Collections.sort(sportsMans, comparator);
}

Instantiating and using an enum singleton

Say you have an enum singleton:
public enum Elvis {
INSTANCE;
private int age;
private Elvis() { age = 42; }
public int getAge() { return age; }
public void leaveTheBuilding() { System.out.println("I'm outta here."); }
}
Question: how do you then use it? Is it like this:
int a = Elvis.INSTANCE.getAge();
Elvis.INSTANCE.leaveTheBuilding();
// and so on, using Elvis.INSTANCE
or is it preferable to instantiate it "explicitly" and then use that instance, like so:
Elvis elvis = Elvis.INSTANCE;
int a = elvis.getAge();
elvis.leaveTheBuilding();
// and so on, using elvis
I'm tempted to use the latter to avoid having the ugly .INSTANCE notation everywhere. But is there a drawback to doing that? (Aside from the one extra line of code to instantiate.)
It doesn't matter. One uses a local variable, and the other doesn't. Use what you find the most readable.
It seems to me, that you can better use a static class in this case:
public class Elvis {
private static int age = 42;
private Elvis() {}
public static int getAge() { return age; }
public static void leaveTheBuilding() {
System.out.println("I'm outta here.");
}
}
And then do:
int a = Elvis.getAge();
Elvis.leaveTheBuilding();
// etc.

Categories