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
Related
public class demo
{
public static void main(String[] args)
}
I just started to learn java, I have c++ experience, and the layout confuses me. for example if I declare a function in the demo class would that make it a function or method. also if I want to declare a class can I declare it outside the demo class or it must be inside the demo class.
thank you.
You have already declared it. The thing you are missing is your function body.
public static void main(String[] args)
should be
public static void main(String[] args){
//DO Some Stuff
}
Now here is some additional info:
The main function will be started whenever the application is started and the
String[] args
are the arguments that you are going to pass while starting the application.
You can declare as many functions as you want within your class
public class demo{
public static void main(String[] args){
//Do Some Stuff
}
private void someFunction(){
//Do Some Stuff
}
}
For more you can start learning some basics from the internet. There are tons of tutorials. Hope that helps. :)
you can write code like that
public class Emp{
//Instance variable or class level variable even variable as static
String id;
String name;
//static variable
static int count=0;
{
//non static block
}
static{
// static block
}
public Emp(){
//default constructor
}
//parameterized constructor
public Emp(String id, String name){
this.id=id;
this.name=name;
}
// Non-Static Method
public String getId(){
return id;
}
public String getName(){
return name;
}
//Main method
public static void main(String[] args){
//Instance of class
Emp emp=new Emp("1","Xyz");
System.out.println(emp.getId());
System.out.prinln(emp.getName());
}
}
In Java there are no functions. There are only methods.
You can declare methods inside of class definitions. And methods can be static or not static. Just like in C++.
Also there's no need for header files.
Example:
public class Demo {
// This is a constructor
public Demo() {
}
// This is a non-static method
public void method() {
}
// This is a static method.
// (It's also a special entry point to start the program)
public static void main(String[] args) {
}
}
I think it's safe to say that Java is much simpler than C++.
Ps. I capitalized Demo because according to Java's camel case convention, classes should start with an uppercase letter and methods with lowercase.
I have a Java program that should read configuration parameters from file, Like this:
java -jar myapp.jar --config config.txt ...
Once loaded, these parameters do not change and should be accessible by any class in the program.
Is it possible to make these parameters accessible from any class without explicitly adding them as parameter to constructors and methods? For example, I would like to be able to do this:
public class Main {
public static void main(String[] args){
// This list should be visible by any class
List<String> CONFIGS= readMyConfigsFromFile(args[0]);
...
}
}
public class MyClass(){
public MyClass(){
String thisConf= CONFIGS.get(0); // Do something with this conf param taken from Main.
...
}
}
public class MyOtherClass(){
public MyOtherClass(){
String thisConf= CONFIGS.get(0); // Do something with this conf param taken from Main.
...
}
}
...
Is this possible at all? And is it an advisable set up to do? If not, what is the recommended design to go about it?
(I have read similar questions but I'm still unsure if and how it is possible in the situation I described)
You could use the Singleton pattern.
To model it, I assume you have 2 fields in your configuration: a String and an integer.
public class Config {
private static Config INSTANCE;
private final String field1;
private final int field2;
public Config(String field1, int field2) {
this.field1 = field1;
this.field2 = field2;
}
public String getField1() {
return field1;
}
public int getField2() {
return field2;
}
public static Config getInstance() {
if (INSTANCE == null) {
INSTANCE = loadInstance();
}
return INSTANCE;
}
private static Config loadInstance() {
// read your config from properties
String field1 = ...
int field2 = ...
return new Config(field1, field2);
}
}
And then use Config.getInstance() everywhere you need to get that instance.
Please note that this implementation has a flaw: it may be initialized several times if getInstance() gets called from different theads.
Double-checked locking https://en.wikipedia.org/wiki/Double-checked_locking may be used to overcome this flaw if it is important to you to only initialize once.
This solution, like others, would require a mock object to unit test. But I think it's best as it encapsulates the arguments in an immutable object. This also makes thread-safety a non-issue. Use a HashMap instead of an array to access these by key instead of index if you prefer:
public class Main {
public static void main(String[] args){
new CONFIG(readMyConfigsFromFile(args[0]).toArray());
...
}
public static final class CONFIG {
private final String[] args;
private static final CONFIG instance;
private CONFIG(String[] args) {
this.args = args;
instance = this;
}
public static CONFIG getInstance() {
return CONFIG.instance;
}
public String[] getArgs(){
return Arrays.copy(this.args, this.args.length);
}
public String getArg(int index) {
return args[index];
}
}
To get arguments:
Main.CONFIG.getArgs();
"Is this possible at all?". Yes, it is. You can easily do it with the help of static in java
public class Config {
private static final List<String> config = new ArrayList<String>();
public static void addConfig(String value){
config.add(value);
}
public static List<String> getConfig(){
return config;
}
}
To add values to config you can do
public static void main(String[] args) {
//Read value from file here in some variable say configValue
Config.addConfig(configValue);
}
To access config
public class MyOtherClass(){
public MyOtherClass(){
Config.getConfig().get(0); // Do something with this conf param taken from Main.
...
}
}
Note above code is not thread safe. You can make it thread safe by adding synchronization concepts
Now "And is it an advisable set up to do?". It depends on your requirements. As you mentioned these values does not change runtime then you can use this. But is the requirement we need to enforce that these values "should not change" once initialized then answer will be different and you should use something like Singleton Pattern and modify to make sure you can only read and not write once the object is constructed. Also note that with static methods, like I suggested, testing becomes really hard.
I must define a class which all it does is hold constants.
public static final String CODE1 = "100";
public static final String CODE2 = "200";
Now I want use these values in other classes. Is it better to use this class as a static class or instantiate it ?
Thanks.
Note : I know enums but in this context, I must use a class.
Just to use the values, you certainly shouldn't instantiate the class. Just because you can access static members as if they were instance members doesn't mean it's a good idea.
If the class really only contains constants - and if you're sure that's a good idea, rather than those constants appearing within classes which are directly related to them - you should make it a final class with a private constructor, so that no-one can pointlessly instantiate it:
public final class Codes {
public static final String CODE1 = "100";
public static final String CODE2 = "200";
// Prevent instantiation
private Codes() {
}
}
Don's answer suggesting using an enum is a very good idea too - it means you can use Code in your API everywhere that you don't need the exact string representation, which prevents you from accidentally using non-code values.
Jons answer is correct, although I want to show you a solution with an enum.
There is a disadvantage in accessing its String value as you have to call Code.CODE1.text() instead of Code.CODE1.
public enum Code {
CODE1("100"), CODE2("200");
private String text;
Codes(String text) {
this.text = text;
}
public String text() {
return text;
}
}
java language spec and JVM spec allow you to do anything you wanted, whether instantiate a class or use final or use other way....
Just use Eclipse and try !
while there is some good practice, Jon Skeet's answer is one good practice.
Java Language is not support global variable
public class ComonFun {
public static final String CODE1 = "100";
public static final String CODE2 = "200";
public static String CODE1(){
return CODE1;
}
public static String CODE2(){
return CODE2;
}
}
implement
public class Main {
public static void main(String[] args) {
System.out.println(ComonFun.CODE1());
System.out.println(ComonFun.CODE2());
}
}
i think that you need simply to declare an interface, you won't need to specify the clause "public static final". and it can be usuable throgh the hall project.
Use them as static, don't go for instantiation.
Even use static import as a benefit.
package coma;
import static coma.ImportStatments.*;
public class UsingClass {
public static void main(String[] args) {
System.out.println(CODE1);
}
}
And the class with final variables would look like this:
package coma;
public class ImportStatments {
public static final String CODE1 = "100";
public static final String CODE2 = "200";
}
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;
}
}
I still cannot fully understand this static and non static.
public static void main(String args[]){
staticClass.setString("hey there");
System.out.println(staticClass.getString2());
//expecting to be blank
NonStaticCalling nonStaticCalling = new NonStaticCalling();
}
static String aw = "";
public static void setString(String a){
aw =a;
}
public String getString(){
return aw;
}
public static String getString2(){
return aw;
}
public class NonStaticCalling {
staticClass staticClass = new staticClass();
public NonStaticCalling(){
staticClass.getString();
System.out.println(staticClass.getString());
}
}
If i understand correctly. I declare a new object nonstaticcalling. So i assume that the value of the output from that class is "" (blank)
Can someone give me a better exmaple? thanks
When a static variable is set, it is the same for all instances of the class. Static variables are also known as "class variables". I think your confusion is actually about the variable more so than the methods. Take this example with no static variables as a simple example. "name" is the same for all instances of the class "myName" (sorry should've made it capital since it's a class name).
public class myName {
public static String name;
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
public static void main(Strings args[]) {
myName first = new myName();
myName second = new myName();
first.setName("hello");
System.out.println(second.getName()); //prints hello
}
}
Static variables are created only one for all the objects of that StaticClass so you're return the same static variable from newly created object.
For one, you can call
NonStaticCalling.getString2()
but not
NonStaticCalling.getString()
A static method can be called without instantiating the class.
SomeName.setString("hey there");
System.out.println(SomeName.getString2());
//expecting to be blank
SomeName object = new SomeName();
object.setString2("hey there");
System.out.println(object.getString());
public class SomeName
{
static String aw = "";
String aw2 = "";
public SomeName()
{
}
public static void setString(String a){
aw =a;
}
public void setString2(String a){
aw2 =a;
}
public String getString(){
return aw;
}
public static String getString2(){
return aw;
}
}
This will print what you got! so the difference is that in one you are using a static property of the class, this means that if you change it, it changes for every other object using it in the future!
In the second one you are using an "object" or an instance of the class, this means that all variables are only set to that object while it lives! If you create a new one you will have to set up aw2 again for it!