Is it possible to set method level variable as class level variable? - java

I want to set my method level variable as class level variable. Is it possible to set method level variable as class level variable in Java?i want to get method level variable value as class level variable how to get it?
class A {
void m(String s){
String s1 = s;
}
}

I guess that you want (as a basic example)
class A {
String s1;
void m(String s) {
s1=s;
}
}
Note that this is what you do with a setter function:
public class A {
private String s1;
//Since the attribute is private, you need a function to access to the value
public String getS1() {
return this.s1;
}
public void setS1(String s) {
this.s1 = s;
}
}
And you can also pass the dynamic value in the class constructor:
public class A {
private String s1;
public A(String s1) {
this.s1 = s1;
}
//Since the attribute is private, you need a function to access to the value
public String getS1() {
return this.s1;
}
public void setS1(String s) {
this.s1 = s;
}
}

Try this code
class A {
String s;
void m(String s){
this.s=s; //this keyword is used to ambiguity between local variable and class level variable
}
}

If you asking about setting the Instance variable in that method here's how you do it.
String s;//instance var
void m(String s)//s is dynamic value
{
this.s=s;
}

Related

Change and use variable by different methods

I've got a small question because oft a topic I didn't understand. There is one variable in a class. In the first method I want to give her a value. The second method have to change the value of this variable again. The new value of the variable is needed by a third method. I want to change and use this variable on every point of the class. Is this possible? I hope you know what I mean. Thanks for every help!
It is possible.
public class Test{
int counter;
public void initCounter(int initValue){
counter = initValue;
}
public void incCounter(){
counter++;
}
public void decCounter(){
counter--;
}
public void printCounter(){
System.out.println(counter);
}
}
If I understand you correctly, you need to send a variable into the methods so that they can modify it. As I understand, here it could be difficult becuause if you use wrapper types, they can't be modified. In such a case you can create a class that wraps your variable and can change it's values or you can use ready-to-go solutions from third party libraries.
For example, in apache-comons, they have a package:
org.apache.commons.lang3.mutable
That contains mutable wrappers for all primitive types(e.g. MutableInt).
Using your own wrapper or this classes you can modify variable inside methods and keep result saved without returning new values from these methods.
You can do , here an example :
public class PassingV {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public PassingV firsM(PassingV a){
a.setI(1);
return a;
}
public PassingV secondM(PassingV a){
a.setI(2);
return a;
}
public PassingV thirdM(PassingV a){
a.setI(3);
return a;
}
#Override
public String toString() {
return "PassingV [i=" + i + "]";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PassingV v = new PassingV();
System.out.println(v.firsM(v).toString());
System.out.println(v.secondM(v).toString());
System.out.println(v.thirdM(v).toString());
}
}
Result:
Becarful to the types of objects you are using and becarful at the methods (accessors for example ) you define ,or not define in the class .
They can totally change the way how your object has seen from the outside .
Lets modifiy our class a bit and lets see what happen .
Now instead of int i will use a String parameter.
public class PassingV {
private String i;
public String getI() {
return i;
}
public void setI(String i) {
this.i = i;
}
public PassingV firsM(PassingV a){
a.setI("HEY ");
//substring but it return the original value :D
System.out.println(a.getI().substring(2));
return a;
}
public PassingV secondM(PassingV a){
a.setI("JOE ");
return a;
}
public PassingV thirdM(PassingV a){
a.setI("LETS GO");
return a;
}
#Override
public String toString() {
return this.getI() ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PassingV v = new PassingV();
System.out.println(v.firsM(v).toString());
System.out.println(v.secondM(v).toString());
System.out.println(v.thirdM(v).toString());
}
}
Result:
As you can see with String object something changed , it happen because is
Immutable object
Following this link you can read more about Immutable Objects

How to read and write to variables of an abstract class

Put simply, I have an abstract class containing several variables and methods. Other classes extend this abstract class, yet when I try to read the private variable in the abstract class by calling getter methods inside the abstract class, it returns null as the value of the variable.
public class JavaApplication {
public static void main(String[] args) {
NewClass1 n1 = new NewClass1();
NewClass2 n2 = new NewClass2();
n1.setVar("hello");
n2.print();
}
}
public class NewClass1 {
public String firstWord;
public void setVar(String var) {
firstWord = var;
}
public String getVar () {
return firstWord;
}
}
public class NewClass2 extends NewClass1{
public void print() {
System.out.println(makeCall());
}
public String makeCall() {
return getVar();
}
}
Still prints out null.
Until the String is initialized, it will be null. You should probably have a constructor in the abstract class to set it.
public abstract class Command
{
String firstWord; // = null
protected Command(){}
protected Command( String w )
{
firstWord = w;
}
//...
}
public class Open extends Command
{
public Open()
{
this( "your text" );
}
public Open( String w )
{
super( w );
}
// ...
}
If you need to modify the firstWord string everytime execute() is called then it may not be necessary to use a constructor with a String parameter (I added a default constructor above). However, if you do it this way then either
You must make sure setFirstWord() is called before getFirstWord(), or,
Handle the case when getFirstWord() returns null. This could be by simply using a default value (maybe determined by each subclass) or something else, like failing to execute.
As I do not know all the details of your implementation I cannot tell you further information.

How to call a variable in another method?

How to call a variable in another method in the same class?
public void example(){
String x='name';
}
public void take(){
/*how to call x variable*/
}
First declare your method to accept a parameter:
public void take(String s){
//
}
Then pass it:
public void example(){
String x = "name";
take(x);
}
Using an instance variable is not a good choice, because it would require calling some code to set up the value before take() is called, and take() have no control over that, which could lead to bugs. Also it wouldn't be threadsafe.
You make it an instance variable of the class:
public class MyClass
{
String x;
public void example(){ x = "name"; } // note the double quotes
public void take(){ System.out.println( x ); }
}
Since they are in different scopes you can't.
One way to get around this is to make x a member variable like so:
String x;
public void example(){
this.x = "name";
}
public void take(){
// Do stuff to this.x
}
public class Test
{
static String x;
public static void method1
{
x="name";
}
public static void method2
{
System.out.println(+x);
}
}

Declaring a nested class in Java

I'm a bit confused with subclasses.
Here's my code:
public class MedHistory {
private String grafts;
private String allergies;
private String diseases;
private String surgeries;
private String medicalTreatment;
//Constructors (#2)
public MedHistory(String allergies, String diseases, String grafts,
String treatments, String surgeries) {
this.allergies=allergies;
this.diseases=diseases;
this.grafts=grafts;
this.medicalTreatment=treatments;
this.surgeries=surgeries;
}
public MedHistory() {
this.allergies="";
this.diseases="";
this.grafts="";
this.medicalTreatment="";
this.surgeries="";
}
//Getters
public String getGrafts() {
return grafts;
}
public String getAllergies() {
return allergies;
}
public String getDiseases() {
return diseases;
}
public String getSurgeries() {
return surgeries;
}
public String getMedicalTreatment() {
return medicalTreatment;
}
//Setters
public void setGrafts(String grafts) {
this.grafts = grafts;
}
public void setAllergies(String allergies) {
this.allergies = allergies;
}
public void setDiseases(String diseases) {
this.diseases = diseases;
}
public void setSurgeries(String surgeries) {
this.surgeries = surgeries;
}
public void setMedicalTreatment(String medicalTreatment) {
this.medicalTreatment = medicalTreatment;
}
public class FemMedHistory extends MedHistory {
private List<Birth> births = new ArrayList<Birth>();
//Constructors (#2)
public FemMedHistory(String allergies, String diseases, String grafts,String treatments, String surgeries, List<Birth> birthlist) {
super(allergies,allergies,grafts,treatments,surgeries);
this.births=birthlist;
}
public FemMedHistory() {
super();
this.births=null;
}
//Getter
public List<Birth> getBirths() {
return this.births;
}
//Setter
public void setBirths(List<Birth> list) {
this.births=list;
}
}
}
When I try to create an new FemMedHistory object like this:
List<Birth> list = new ArrayList<Birth>();
list.add(new Birth(new GregorianCalendar(2011,4,10),"kaisariki",4));
FemMedHistory female = new FemMedHistory("allergia2","astheneia2","emvolia2","farmekeutiki agwgi2", "xeirourgeia2", list);
I get the error:
No enclosing instance of type MedHistory is accessible. Must qualify
the allocation with an enclosing instance of type MedHistory (e.g.
x.new A() where x is an instance of MedHistory).
So, which is the right way to use a subclass?
When you declare a nested class it only available through the Outer class.
To access it outside, you will need to either make the FemMedHistory class static.
public static class FemMedHistory extends MedHistory {...}
access it through the MedHistory class
MedHistory.FemMedHistory myMedHistory = ...
or declare it in it's own Java file.
You have declared your subclass as an inner class, which means that you can't create an instance of it without first creating an instance of the containing class.
The most common way to solve this is to declare it as a separate class, which would get rid of your error.
Long story short: cut all the FemMedHistory code and paste it into FemMedHistory.java. The way it is now you have involved Java concepts which you have not yet mastered. Also, that class really does belong in a separate file.

Don’t call subclass methods from a superclass constructor

Consider the following code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package example0;
/**
*
* #author yccheok
*/
public class Main {
static class A {
private final String var;
public A() {
var = getVar();
// Null Pointer Exception.
System.out.println("var string length is " + var.length());
}
public String getVar() {
return "String from A";
}
}
static class B extends A {
private final String bString;
// Before B ever constructed, A constructor will be called.
// A is invoking a overriden getVar, which is trying to return
// an initialized bString.
public B() {
bString = "String from B";
}
#Override
public String getVar() {
return bString;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
B b = new B();
}
}
Currently, in my mind, there are two ways to avoid such problem.
Either making class A final class.
static final class A {
private final String var;
public A() {
var = getVar();
// Null Pointer Exception.
System.out.println("var string length is " + var.length());
}
public String getVar() {
return "String from A";
}
}
Or
Making getVar method final
static class A {
private final String var;
public A() {
var = getVar();
// Null Pointer Exception.
System.out.println("var string length is " + var.length());
}
public final String getVar() {
return "String from A";
}
}
The author trying to suggest ways to prevent the above problem. However, the solution seems cumbersome as there are some rules to be followed.
http://benpryor.com/blog/2008/01/02/dont-call-subclass-methods-from-a-superclass-constructor/
Beside making final and the author suggested way, is there more ways to prevent the above problem (Don’t call subclass methods from a superclass constructor) from happen?
Making getVar method final
This is definitely what you need to do.
If you're relaying on the functionality of a method to initialize an object, you shouldn't let subclasses broke that method.
Answering your question, other way to prevent it is to make getVar private in A.
See this simplified version of your code:
// A.java
class A {
private final String var;
public A(){
var = getVar();
var.length();
}
private String getVar(){
return "This is the value";
}
}
class B extends A {
private final String other;
public B(){
other = "Other string";
}
public String getVar(){
return other;
}
}
class Main{
public static void main( String [] args ) {
new B();
}
}
BTW, why did you put those as static nested classes, just to create confusion?

Categories

Resources