How to override class variable value - java

This is sample reference example, for what I am looking Solution
Reference Example:
Here demoName is global variable
Somehow I need to define that variable on Class level which is : String demo = demoName;
Now it needs to override variable value with local variable, when it call from local method.
void test(String name) {
demoName = name;
System.out.println("Local Value:" + demoName);
System.out.println("Global Value:" + demo);
}
Here demoName becoming override with parameter value, But when +demo is taking class level value which is XYZ, I want it to be abc.
class demo1 {
public static String demoName = "xyz";
}
public class demos extends demo1 {
String demo = demoName;
void test(String name) {
demoName = name;
System.out.println("Local Value:" + demoName);
System.out.println("Global Value:" + demo);
}
#Test
public void testtest() {
test("abc");
}
}
I want both value to be "abc" .

Because demoName is public, you can reassign it from anywhere using Demo.demoName = "abc";, no need for a subClass at all.
However, using a public static variable and reassignating is awful. If you just want to override it at instance level in a subclass, you should use an accessor and override the accessor :
public static class Demo {
public static String demoName = "xyz";
public String getDemoName() {
return demoName;
}
}
public static class Demos extends Demo {
private String demoNameOverride;
#Override
public String getDemoName() {
return demoNameOverride;
}
}

String is Immutable in java
Note: when two String variables are referencing to the same object, if one variable changes its object at any stage , it only changes that variable Object not the other variable Objects.
String demo = demoName;
at this line of code both variables are referencing to the same object xyz
which means demo and demoName have xyz. the reason why it is not changing its object after
#Test
public void testtest() {
test("abc");
}
because String is immutable in Java. please refer Why is String immutable in Java?
https://www.programcreek.com/2013/04/why-string-is-immutable-in-java/
ex:
static String a="Helloworld";
static String b=a;
public static void main(String[] args) {
System.out.println(a);
System.out.println(b);
a="World";
System.out.println(a);
System.out.println(b);
}
output:
Helloworld
Helloworld
World
Helloworld
this is how your programme logic flows now and b is referencing to its previous Object Only.after you change the String Value and again the reference has to be done.The below example will give you the idea.
public class Demo1 {
public static String demoName = "xyz";
}
class Demo extends Demo1 {
static String demo = demoName;
public void test(String variableName) {
//initially i am calling both varaibles which you assign
System.out.println(demoName);
System.out.println(demo);
// i am assigning the "abc" to demoName and calling both varaibales
demoName = variableName;
System.out.println(demoName);
System.out.println(demo);
// Now i am assigning the "abc" to demo and calling both varaibales
this.demo = variableName;
System.out.println(demoName);
System.out.println(demo);
}
public static void main(String[] args) {
Demo dem = new Demo();
dem.test("abc");
}
}
The Output is :
xyz
xyz
abc
xyz
abc
abc

Related

Getting issue in adding data to List

I have two classes namely Test and Demo and in Demo class I have a class variable namely List. I somehow need to put/add the given two strings into List but it will only accept objects of Test class. Is there a way I can add the given strings to List.
class Test{
List<Test> getdataFromDemo(){
return Demo.getData;
}
}
class Demo{
public static List<Test> getData=new LinkedList<Test>;
static void D1(){
String str1="TestOne";
String str2="TestTwo";
}
getData.add(str1);//need to add str to getData but this is showing error
getData.add(str2);
System.out.println(getData)
You are trying to store a String in your generic list of Test. You need to create an attribute in Test of the type String and set it within the constructor. Then you need to add the new objects of Test with the Strings str1 and str2 in the constructor to the list.
public class Test {
public String name;
Test(String name) {
this.name = name;
}
List < Test > getdataFromDemo() {
return Demo.getData;
}
}
class Demo {
public static List < Test > getData = new LinkedList < Test > ();
public static void main(String[] args) {
String str1 = "TestOne";
String str2 = "TestTwo";
getData.add(new Test(str1)); // need to add str to getData but this is showing error
getData.add(new Test(str2));
System.out.println(getData);
}
}
Add a field variable in test class of string and initialize its in constructor.
or just set the string directly using setters and fetch it using getters.
class Test{
public String testString;
public void setTestString() {
this.testString=testString;
}
public String getTestString() {
return this.testString;
}
List<Test> getdataFromDemo(){
return Demo.getData;
}
}
class Demo{
public static List<Test> getData=new LinkedList<Test>;
static void D1(){
String str1="TestOne";
String str2="TestTwo";
}
Test test1 = new Test()
test1.setTestString( str1);
getData.add( test1);//need to add str to getData but this is showing error
Test test2 = new Test()
test2.setTestString( str2);
getData.add(test2);
System.out.println(getData)

Return a string value to the pass-in varibale from the argument in a function

I want the pass-in variable "aaa" to be returned the value from the argument of the function. I really need my argument in the function to be defined as String, and want whatever change of the argument in the function to be return to the pass-in variable.
How do I make this happen in Java? If anyone could help I will appreciate!
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
aaa = "123";
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc(demo.aaa);
System.out.println(demo.aaa);
}
}
You cannot do it like this: String class in Java is immutable, and all parameters, including object references, are passed by value.
You can achieve the desired result in one of three ways:
Return a new String from a method and re-assign it in the caller,
Pass mutable StringBuilder instead of a String, and modify its content in place, or
Pass an instance of DeppDemo, and add a setter for aaa.
Here are some examples:
public class DeppDemo {
private String aaa;
private StringBuilder bbb = new StringBuilder();
public String abc() {
return "123";
}
public void def(StringBuilder x) {
x.setLength(0);
x.append("123");
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.aaa = demo.abc(); // Assign
demo.def(demo.bbb); // Mutate
System.out.println(demo.aaa);
}
}
It's really unclear what you're asking, but it sounds like you're trying to change the content of a variable passed into a function. If so, you can't in Java. Java doesn't do pass-by-reference.
Instead, you pass in an object or array, and modify the state of that object or array.
public class DeppDemo {
public void abc(String[] aaa) {
aaa[0] = "123";
}
public static void main(String[] args) {
String[] target = new String[1];
DeppDemo demo = new DeppDemo();
demo.abc(target);
System.out.println(target[0]);
}
}
But if you're asking how to update the aaa field using the aaa argument, then you need to qualify your reference to the field using this., since you've used the same name for both. Or change the name of the argument.
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
this.aaa = aaa;
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc("New value");
System.out.println(demo.aaa);
}
}

String s1=new String("demo"); While printing why does it give output as the given string?

If we create a String like below and print the value:
String s=new String("demo");
System.out.println(s);
...the output is:
demo
Good. This is the expected output. But here String is a class. Remember that. Below is another example. For example, take a class like this:
class A
{
public static void main (String args[])
{
A a =new A();
A a1=new A("hi"); //we should create a Constructor like A(String name)
System.out.println(a1); //here O/P is address
}
}
My doubt is that I created the A instance in the same way I created the new String object, and I printed that object. So why does it not print the given String for the instance of A?
You need to override the Object#toString() in your class. By default, the toString() method of Object is called.
Also, to print the value, you just need to override the method as internally a call will be made to the toString() method when this statement is executed.
System.out.println(a1);
Sample overriden toString() method.
#Override
public String toString() {
// return a string value
return "The String representation of your class, as per your needs";
}
You have to override toString() method in your class the way you want to print something when call System.out.println();. In String class toString() method has override and you will get out put above due to that.
As pointed out already, you need to override the default toString() method inherited from the Object class. Every class automatically extends the Object class, which has a rather simple toString(), which can't know how to turn your particular object into a String. Why should it, especially if your class is arbitrarily complex? How is it supposed to know how to turn all your class's fields into a "sensible" string representation?
In the toString() of your class, you need to return the string that you want to represent your class with. Here is a simple example:
class A {
String foo;
public A(String foo) {
this.foo = foo;
}
public String toString() {
return foo;
}
}
public class sample {
public static void main(String[] args) {
A a = new A("Hello world!");
System.out.println(a);
}
}
String is a class whose purpose is to hold a string value and will return that value if referenced. When you use other classes, you will usually want to add other behavior. If you want to use the class to hold different values that you can set (on object creation or later in processing) you may want to use "setter" and "getter" methods for such values.
Here is an example:
public class Snippet {
private static final String C_DEFAULT_VALUE = "<default value>";
private String name;
private static Snippet mySnippet;
public Snippet() {
}
public Snippet(String value) {
setName(value);
}
/**
* #param args
*/
public static void main(String[] args) {
if (args != null && args.length > 0) {
mySnippet = new Snippet(args[0]);
} else {
mySnippet = new Snippet(C_DEFAULT_VALUE);
}
System.out.println(mySnippet.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

How to access field whenever its name is same with local variable?

I have a field and a local variable with same name. How to access the field?
Code:
String s = "Global";
private void mx()
{
String s = "Local";
lblB.setText(s); // i want global
}
In c++ use :: operator like following:
::s
Is were :: operator in Java?
That's not a global variable - it's an instance variable. Just use this:
String s = "Local";
lblB.setText(this.s);
(See JLS section 15.8.3 for the meaning of this.)
For static variables (which are what people normally mean when they talk about global variables), you'd use the class name to qualify the variable name:
String s = "Local";
lblB.setText(ClassDeclaringTheVariable.s);
In most cases I prefer not to have a local variable with the same name as an instance or static variable, but the notable exception to this is with constructors and setters, both of which often make sense to have parameters with the same name as instance variables:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
You can use "this" keyword to do this.
Example:
public class Test {
private String s = "GLOBAL";
public Test() {
String s = "LOCAL";
//System.out.println(this.s);
//=> OR:
System.out.println(s);
}
public static void main(String[] args) throws IOException {
new Test();
}
}
Using this keyword you can use the global one but inside the same class. Or simply you can declare global variable static and access the same using classname.variable name.
Yes you can also use
class _ name.Globalvariable_name
Class simple
{
static int i;
public static void main(string args[])
{
int i=10;
System.out.println("Local Variable I =" +i) ;
system.out.println("Global variable I =" +Simple.i)
}
}

Get String From Another Method?

I have two methods, the first one creates a string, then I want to use that string in the second method.
When I researched this, I came across the option of creating the string outside of the methods, however, this will not work in my case as the first method changes the string in a couple of ways and I need the final product in the second method.
Code:
import java.util.Random;
import java.util.Scanner;
public class yaya {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Random ran = new Random();
int ranNum = ran.nextInt(10);
input = input + ranNum;
}
public void change(String[] args) {
//more string things here
}
}
Create an instance variable:
public class MyClass {
private String str;
public void method1() {
// change str by assigning a new value to it
}
public void method2() {
// the changed value of str is available here
}
}
You need to return the modified string from the first method and pass it into the second. Suppose the first method replaces all instances or 'r' with 't' in the string (for example):
public class Program
{
public static String FirstMethod(String input)
{
String newString = input.replace('r', 't');
return newString;
}
public static String SecondMethod(String input)
{
// Do something
}
public static void main(String args[])
{
String test = "Replace some characters!";
test = FirstMethod(test);
test = SecondMethod(test);
}
}
Here, we pass the string into the first method, which gives us back (returns) the modified string. We update the value of the initial string with this new value and then pass that into the second method.
If the string is strongly tied to the object in question and needs to be passed around and updated a lot within the context of a given object, it makes more sense to make it an instance variable as Bohemian describes.
Pass the modified string in the second method as an argument.
create a static variable used the same variable in both the method.
public class MyClass {
public string method1(String inputStr) {
inputStr += " AND I am sooo cool";
return inputStr;
}
public void method2(String inputStr) {
System.out.println(inputStr);
}
public static void main(String[] args){
String firstStr = "I love return";
String manipulatedStr = method1(firstStr);
method2(manipulatedStr);
}
}
Since you mentioned that both methods should be able to be called independently, you should try something like this:
public class Strings {
public static String firstMethod() {
String myString = ""; //Manipulate the string however you want
return myString;
}
public static String secondMethod() {
String myStringWhichImGettingFromMyFirstMethod = firstMethod();
//Run whatever operations you want here and afterwards...
return myStringWhichImGettingFromMyFirstMethod;
}
}
Because both of these methods are static, you can call them in main() by their names without creating an object. Btw, can you be more specific about what you're trying to do?

Categories

Resources