Static method vs non static method java better understanding - java

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!

Related

How to hide a static variable in Java

I have three classes with same methods and only constants are different. So what I wanted is to create one base class, which contains all the methods and to add three child classes which contain only constant variables. It looks like it is not possible to do so because of the dynamic binding. Please look at the example:
public class Parent {
static String MY_CONSTANT = "bla bla";
public void printSomething() {
System.out.println(MY_CONSTANT);
}
}
public class Child extends Parent {
static String MY_CONSTANT = "hello world";
}
public class Greetings {
public static void main(String[] args) {
Child hey = new Child();
hey.printSomething();
}
}
The output is "bla bla", but I want the output to be "hello world".
Is there some solution for this problem?
You'll have to override the printSomething() method:
public class Child extends Parent {
static String MY_CONSTANT = "hello world";
#Override
public void printSomething() {
System.out.println(MY_CONSTANT);
}
}
It might be cleaner, though, to have a method that returns the value of the static variable. Then you can override that method, and call it from the base class:
public class Parent {
static String MY_CONSTANT = "bla bla";
public String getConstant() {
return Parent.MY_CONSTANT;
}
public void printSomething() {
System.out.println(getConstant());
}
}
public class Child extends Parent {
static String MY_CONSTANT = "hello world";
#Override
public String getConstant() {
return Child.MY_CONSTANT;
}
}
public class Greetings {
public static void main(String[] args) {
Child hey = new Child();
hey.printSomething();
}
}
How to hide a static variable in Java?
This is all you can do for variables: hide them. Although variables can be inherited, they cannot be overridden.
As actual values are class-specific and static, the only way to reuse a method in this scenario, is by making it take parameters:
public class Parent {
static String MY_CONSTANT = "bla bla";
public void printSomething(String something) {
System.out.println(something);
}
//Essentially, Parent.MY_CONSTANT becomes just the default
public void printSomething() {
System.out.println(MY_CONSTANT);
}
}
And the child can choose what it sends (overriding is basically to reuse the API):
public class Child extends Parent{
static String MY_CONSTANT = "hello world";
#Override
public void printSomething() {
//MY_CONSTANT is hidden and has "hello world"
super.printSomething(MY_CONSTANT);
}
}
The above design allows calls from the test class to behave predictably (or, rather, intuitively):
Child hey = new Child();
//Behaves as Child.
hey.printSomething();
EDIT: Since the getter is an instance method (understandable as you depend on the instance type to read the correct value), you can expose to children the field, or a setter, and all sorts of hiding would be suppressed completely:
public class Parent {
protected String myConstant = "bla bla";
public void printSomething() {
System.out.println(this.myConstant);
}
}
And children would just have to set the value in an initialization block:
public class Child extends Parent{
public Child() {
myConstant = "hello world";
}
}
public class Parent {
static String MY_CONSTANT = "bla bla";
public void printSomething() {
System.out.println(Child.MY_CONSTANT);
}
}
public class Child extends Parent{
static String MY_CONSTANT = "hello world";
#Override
public void printSomething() {
super.printSomething(); // definition define in parent class
}
}
public class LeapTEST {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Child child = new Child();
child.printSomething();
}
}
If you want to use a constant you should combine the static modifier with the final one. The final modifier indicates that the value of this field cannot change (have a look to this link, in the related section). (A static variable is common for all instances of the class. A final variable can not change after it has been set the first time).
If you have a look the Java Language Specification:
A hidden field can be accessed by using a qualified name if it is
static, or by using a field access expression that contains the
keyword super or a cast to a superclass type.
So you can refer a static variable outside the class using ClassName.myStaticVariable:
And since you should access them in this way, there is also no need to worry about hiding them.
I reached the same problem and my solution instead of extending the parent class was by using an enum like this:
public enum MyEnum {
PARENT("Parent constant"),
CHILD("Child constant");
private String myConstant;
MyEnum(String s) {
myConstant = s;
}
public void printConstant(){
System.out.println(myConstant);
}
}
And then, call the printConstant method of the desired enum like:
MyEnum.CHILD.printConstant();
Of course, this is limited but it suites my case so i hope it will help someone too.

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

JAVA: I'm trying to pass a string as a parameter in a new instance of a class but keep getting an error

I'm trying to pass a string when creating a new instance of my Palindrome class but it keeps throwing errors at me, Any help?
public class Palindrome {
public String input;
public void Palindrome(String stringinput){
this.input = stringinput;
}
}
public class PalindromeTest {
public static void main(String[] args) {
Palindrome p = new Palindrome("test"); //i get an error here
}
}
If you're trying to define a constructor, this
public void Palindrome(String stringinput){
should be
public Palindrome(String stringinput){
Otherwise it is considered a method with a return type of void.
The void keyword tells the compiler that this is a method signature, not a constructor.
public void Palindrome(String stringinput){
this.input = stringinput;
}
The Palindrome class doesn't have an argumented constructor. It has only default non-arg constructor. I think you have mistaken to add void to public void Palindrome(String stringinput){} method. Because, you have made it as a method not as a constructor.

java - can a class type parameter from a static main class be passed to another class

I have 2 classes the static main class and class B. I'm trying to pass main to B, where there is a method that sets fields.
Can this be done?
If so, could you please provide examples?
public static void main(String[] args) {
ArrayList a = new ArrayList()
class b = new class()
b.update(b);
}
class a {
public void update(ArrayList a) {
//updates the encapsulated arrayList field
}
}
The error message keeps on saying that one is static and the other is non-static, but they should be pointing the same object
I'm not entirely sure what you are trying to do, but here is an example that shows that you can pass an instance of the main class into another class:
public class A {
private String str = null;
public static void main(String[] args) {
A a = new A();
B b = new B(a);
System.out.println(a.getStr());
}
public String getStr() {
return this.str;
}
public void setStr(String str) {
this.str = str;
}
}
public class B {
public B(A a) {
a.setA("hello");
}
}
Running this code will print out hello.
main is static and public, so you can call it from any other class as any other public static method: statically.
if you have a class A that contains a
public static void main(String[] args)
method, then class B can call this method like
A.main(s);
where s is String[]
your question is far from clear, so I suggest you to add more code samples to make it clear what you're really trying to do.

Utilizing Public Final Classes Java

I would just like a clear example of how to instantiate a public final class in Java. I have to use a method from a class like this for a project, and have no idea how to instantiate it in the first place. Very difficult to find a clear example and explanation of the proper syntax. Thanks for the help.
public class Test {
public static void main(String[] args) {
Project pro = new Project();
pro.getName();
}
}
final class Project{
public String getName(){return "";}
}
===============================
A final class can be created like a normal class, Only thing is it can not be extended
This is an example
public class del {
public static void main(String args[])
{
x x1=new x();
System.out.println(x1.u());
}
}
final class x
{
public String u()
{
return "hi";
}
}
As you can see,x is a final class and have a method u which returns a string.
I am instatiating x in class del and calling its method u.
The output is hi
For more info click on final
final class Test{
public void callMe(){
System.out.println("In callMe method.");
}
}
public class TestingFinalClass{
public static void main(String[] args){
Test t1 = new Test();
t1.callMe();
}
}
Output : In callMe method.
final in java is applied to variable,method,class
final variable : the variable can not be signed with another value.
final method : the method cannot not be overridden.
final class : the class cannot extended.
The best example is String class in java. public final class String you can access the methods of String class as normal.
Some links
final keyword
String class
public class Test {
public static void main(String[] args) {
StdRandom stdRandom = StdRandom.getInstance(); /* this will retun an instance of the class, if needed you can use it */
int result =StdRandom.uniform(1);
System.out.println(result);
}
}
final class StdRandom{
private static StdRandom stdRandom = new StdRandom();
private StdRandom(){
}
public static StdRandom getInstance(){
return stdRandom;
}
public static int uniform(int N){
// Implement your logic here
return N;
}
}

Categories