Why my access to non static string variable doesn't work - java

Why my access to non static string variable doesn't work. Try to do it and my IDE found it already but when I run it show "Cannot find symbol"
Please help me, Thank You.
public class Main
{
public static void main(String[] args)
{
testWrong obj = new testWrong();
System.out.println(obj.public_non_static()); //Doesn't Work
}
}
public class testWrong
{
public String public_non_static = "It is Public non Static";
public void in_non_static_method()
{
testWrong obj1 = new testWrong();
obj1.public_non_static(); //Doesn't Work
}
public static void in_static_method()
{
testWrong obj2 = new testWrong();
obj2.public_non_static(); //Doesn't Work also
}
}

You have a variable named public_non_static but you try to access a method with that name which does not work in Java.
on the other hand you should not get used to access variables in other classes directly since it violates the most important OO principle information hiding/encapsulation.
The same is true for getter/setter methods which should only be used on stupid data transfer objects (DTOs) or Value Objects which have no (business) logic.

You are accessing like a method :public_non_static();
Use this instead : obj2.public_non_static;
And since you are like very new to OOP, it's the best practice to not to use public keyword and you should make them private and make getters and setters for them.

Related

How to handle static in java

I got into programming a bit obliquely with Bukkit and thus didn't learn some things properly. But since I've been doing real stuff for a while now I wanted to ask how to deal with static.
I know that you should avoid static as most as possible.
Should you then call external functions like this?
//Another Class
public void exampleMethodInAnotherClass() {
system.out.prinln("Hi :D");
}
//Main
public static void main(String[] args) {
new AnotherClass().exampleMethodInAnotherClass();
}
//OR
public static void exampleMethodInAnotherClass() {
system.out.println("Hi :D");
}
public static void main(String[] args) {
AnotherClass.exampleMethodInAnotherClass();
}
Now it's about the type of function that you use if the function is too much used in your code like System.out.println then make it static *(static function are mostly common in maths and helper classes).
OH the static keyword , My most hero in the programming!
I know that you should avoid static as most as possible.
no that's not true in the most cases the programmer that are student or new in the programming think it's best Idea that we have use static key but it's important to know the why we use static.
after you use static key the variable imidediately going to memory and you can accsess it directly by calling the refrence! and it's the package and class with the variable name but the static method is in the memory and if you change it from some where in your code the data change , see some example :
public class Test {
static String MESSAGE= "";
public static setMessage(String message){
MESSAGE = message;
}
public static void showMessage(){
System.out.println(MESSAGE);
}
}
----------------
Calling from another class
public static void showMessage(){
System.out.println(Test.MESSAGE);
}
if you run the program and change the message with the showMessage method you can get the message and if you need you can call the MESSAGE by reference Like ClassName.MESSAGE or create object from your class with new Keyword but your MESSAGE variable is static and in your memory after running your code so the use new keyword to call it not nesssasery and you can call it directly ! remember using the static variable in mini or script cases or test is good idea but if you create Enterprise project using static method or variable without knowledge about it it's bad idea! because , I most use static keyword for method or variable I need always return same result or work straight work I need! like show the time , convert date or etc... but don't use for changing the data The example I share it's good ref for know the problem.
Good ref for know the static internal work it's here

Expression that behaves differently inside a static method

I'm trying to write an expression or series of statements of Java source code that when written inside a static method evaluates to null, but if the method is non-static evaluates to this.
My initial idea was to 'overload' on static vs non-static, as below:
public class test {
public void method1() {
System.out.println(getThisOrNull());
}
public static void method2() {
System.out.println(getThisOrNull());
}
private static Object getThisOrNull() {
return null;
}
private Object getThisOrNull() {
return this;
}
public static void main(String[] args) {
test t = new test();
System.out.println(t);
t.method1();
t.method2();
}
}
Unfortunately this isn't actually legal Java, you can't 'overload' like that and it just gives a compiler error:
test.java:14: error: method getThisOrNull() is already defined in class test
private Object getThisOrNull() {
^
1 error
Clearly in an ideal world I wouldn't write it like that to begin with, but the problem is this code will be generated automatically by a tool that is not really semantically or syntactically enough to distinguish between the static vs non-static case.
So, how can I write some source code that, although byte for byte identical compiles and behaves differently in depending on the presence of the static modifier for the method?
This can be achieved with a trick and a bit of help from Java's reflection facilities. It's ugly, but it works:
import java.lang.reflect.Field;
public class test {
public void method1() {
System.out.println(getThisOrNull(new Object(){}));
}
public static void method2() {
System.out.println(getThisOrNull(new Object(){}));
}
private static Object getThisOrNull(final Object o) {
for (Field f: o.getClass().getDeclaredFields()) {
if (f.getType().equals(test.class)) {
try {
return f.get(o);
}
catch (IllegalAccessException e) {
// Omm nom nom...
}
}
}
return null;
}
public static void main(String[] args) {
test t = new test();
System.out.println(t);
t.method1();
t.method2();
}
}
This compiles and runs as hoped for:
test#183f74d
test#183f74d
null
The trick that makes this possible is the use of new Object(){}, which creates a new, anonymous class within the existing method that we're trying to figure out if it's static or not. The behaviour of this is subtly different between the two cases.
If the goal were just to figure out if the method is static or not we could write:
java.lang.reflect.Modifiers.isStatic(new Object(){}.getClass().getEnclosingMethod().getModifiers())
Since we want to get this (when available) we need to do something slightly different. Fortunately for us classes defined within the context of an instance of an object in Java get an implicit reference to the class that contains them. (Normally you'd access it with test.this syntax). We needed a way to access test.this if it existed, except we can't actually write test.this anywhere because it too would be syntactically invalid in the static case. It does however exist within the object, as a private member variable. This means that we can find it with reflection, which is what the getThisOrNull static method does with the local anonymous type.
The downside is that we create an anonymous class in every method we use this trick and it probably adds overheads, but if you're backed into a corner and looking for a way of doing this it does at least work.

Encapsulating what doesn't vary?

It's a common practice to encapsulate code that often changes. In fact, it is often in the form of using an object to delegate the varying logic to. A sample would be the following:
public class SampleClass {
Object obj = new ObjectWithVaryingMethod();
public SampleClass(Object obj){
this.obj=obj;
}
public String getString(){
return obj.toString();
}
public static void main(String args[]){
SampleClass sampleClass=new SampleClass(new ObjectWithVaryingMethod());
System.out.println(sampleClass.getString());
}
}
class ObjectWithVaryingMethod{
#Override
public String toString(){
return "Hi";
}
}
Can you suggest what problems I may encounter when "encapsulation" is done on what doesn't vary? I find it to be a good coding conduct when the main class itself is the one that is often subject to change or improvement. A sample would be the following. In this second case, retrieving "Hi", which is the part that doesn't vary, was "encapsulated" in another class.
public class SampleVaryingClass {
public static void main(String args[]) {
//here I may opt to print getHi's value on sysout or on a dialog
System.out.println(ObjectWithNonVaryingMethod.getHi());
}
}
In a completely different class...
public class ObjectWithNonVaryingMethod {
private static final String hi = "Hi";
//"Hi" should always be returned
public static String getHi() {
return hi;
}
}
Can you give some pro's and con's on doing this?
Both code cannot be compared each other. One is static, another one isn't. I hope you understand the concept of encapsulating the object in the first code. Here is the pros and cons for the second one. Remember that static is "generally" bad, and do not support concurrency by default.
pros:
With getHi, you are keeping the string field private, meaning that it cannot be set from other source
Say that you need to do setHi from other source, you can add several guard clauses for it. This is called defensive programming.
public static setHi(String input){
if(input == null) { input = ""; } // can throw exception instead
hi = input;
}
cons:
It is static, needless to say
You don't get any advantage other than guard clauses. If your class is not static, you can swap it with other class implementing same interface, or other class inherited from that class.

The static field should be accessed in a static way

I have different Exception category Enum as below
public enum GSBBCacheCategory {
SEARCH(9001),
UPDATE_PERSECURITY(9002),
CROSS_REFERENCING_PERSECURITY(9003),
METADATA_SEARCH(9004),
REMOVEALL(9005),
UPDATE_BACKOFFICE(9002);
private int exceptionCode;
GSBBCacheCategory(int exceptionCode)
{
this.exceptionCode = exceptionCode;
}
public int getExceptionCode()
{
return exceptionCode;
}
}
public enum GSBBEncryptionCategory {
.
.
.
}
I want to provide one place to access these Enum in client code. Presently I achieved this as below
public class GSBBExceptionCodes
{
public static GSBBDecryptionCategory decryptionCategory;
public static GSBBCacheCategory cacheCategory;
}
Now to access exception code I have do something like below
public static void main(String[] args) {
System.out.println(GSBBExceptionCodes.decryptionCategory.ERRORCODE_DECRYPTION_FAILURE);
System.out.println(GSBBExceptionCodes.cacheCategory.UPDATE_PERSECURITY);
}
Which says “The static field GSBBDecryptionCategory.ERRORCODE_DECRYPTION_FAILURE should be accessed in a static way”
Is it possible to achieve above without any warning?
There are two ways to reference a static member (either a field or a method). One is WhateverClass.theField, and the other is someInstance.theField where someInstance has a compile-time type of WhateverClass. The former is much clearer, and so your IDE is helpfully telling you to use it instead of the latter.
The reason it's better is that referencing a static member by an instance makes it look like the method has something to do with that instance, which it doesn't. Here's a real-life example:
Thread myThread = getMyThread();
myThread.start();
myThread.sleep(5000);
At first blush, it looks like you're asking myThread to sleep for 5 seconds (5000 milliseconds), but that's not what you're doing at all. You're asking the current thread to sleep, because that last line is exactly the same as invoking Thread.sleep(5000). That second example is much more clearly a static method.
Or, here's another example. Let's say your static fields were mutable.
public class Foo {
public static int value = 1;
}
(This public static mutable field is a bad idea for other reasons, but simplifies the example). Now let's say you do:
Foo one = new Foo();
Foo two = new Foo();
one.value = 2;
two.value = 3;
System.out.println(one.value);
System.out.println(two.value);
Kinda looks like that should print "2" and then "3", right? But no -- it'll print "3", "3" because both assignments to .value are in fact to the same, static field. It's just an optical illusion that the one or two instances have anything to do with anything.
Imho, the ability to reference static members from instances is a misfeature. But it's there, so you should avoid it. Which is what the compiler is trying to suggest you do.
Try this :
public static void main(String[] args) {
System.out.println(GSBBDecryptionCategory.ERRORCODE_DECRYPTION_FAILURE);
System.out.println(GSBBCacheCategory.UPDATE_PERSECURITY);
}
You are now accessing the field in a static way which should remove the warning.
It sounds like instead of having these as public static fields, they should be inner classes:
public class GSBBExceptionCodes {
public enum GSBBCacheCategory {
...
}
}

Need help to get two classes to assist each other

i'm currently just fooling around with different classes to test how they work together, but im getting an error message in NetBeans that i cant solve. Here's my code:
class first_class.java
public class first_class {
private second_class state;
int test_tal=2;
public void test (int n) {
if (n>2) {
System.out.println("HELLO");
}
else {
System.out.println("GOODBYE");
}
}
public static void main(String[] args) {
state.john();
TestingFunStuff.test(2);
}
}
class second_class
public class second_class {
first_class state;
public int john () {
if (state.test_tal==2) {
return 4;
}
else {
return 5;
}
}
}
Apparently i can't run the method "john" in my main class, because "non static variable state cannot be referenced from a static context" and the method "test" because "non static method test(int) cannot be referenced from a static context".
What does this mean exactly?
Screenshot of the error shown in netbeans: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/
It means state must be declared as a static member if you're going to use it from a static method, or you need an instance of first_class from which you can access a non-static member. In the latter case, you'll need to provide a getter method (or make it public, but ew).
Also, you don't instantiate an instance of second_class, so after it compiles, you'll get a NullPointerException: static or not, there needs to be an instance to access an instance method.
I might recommend following Java naming conventions, use camelCase instead of under_scores, and start class names with upper-case letters.
The trick here to get rid of the error message is to move the heavy work outside of main. Let's assume that both lines are part of a setup routine.
state.john();
TestingFunStuff.test(2);
We could create a function called setup which contains the two lines.
public void setup() {
state.john();
TestingFunStuff.test(2);
}
Now the main routine can call setup instead, and the error is gone.
public static void main(String[] args) {
setup();
}
However, the other members are correct in that your instantiation needs some cleanup as well. If you are new to objects and getting them to work together might I recommend the Head First Java book. Good first read (note first not reference) and not all that expensive.
Classes can have two types of members by initialization: static and dynamic (default). This controls the time the member is allocated.
Static is allocated at class declaration time, so is always available, cannot be inherited/overridden, etc. Dynamic is allocated at class instantiation time, so you have to new your class if you want to access such members...
It is like BSS vs heap (malloc'd) memory in C, if that helps..

Categories

Resources