I have a variable in x class .And I have another class called "Y" to access the variable. Will it change the value in X class, if the value is incremented in Y class?
Java uses pass by value but we can achieve what you are asking for by passing an object as an argument to a method like this:
public class ClassX {
public int classId;
public ClassX(int id) {
this.classId = id;
}
public void setId(int id) {
classId = id;
}
public int getId() {
return classId;
}
}
public class ClassY {
public static void main(String[] args) {
ClassX cx = new ClassX(100);
ClassY cy = new ClassY();
System.out.println("classId:"+cx.classId);
cy.modifyId(cx); // an object is passed as argument to a method
System.out.println("classId:"+cx.classId);
}
public void modifyId(ClassX classx) {
classx.setId(220);
}
}
Assuming you have it defined like
public int anInteger = 4;
Then yes, it would change.
These are the sorts of things best learned from experimentation, try various ways of structuring the classes, declaring the variable, and accessing it. See what happens.
Yes. All you need is to pass a reference to it to the other class.
Related
Okay, so I have the following code.
Main class
public class Main {
public static void main(String[] args) {
Integer val = 20;
User user = new User(val);
System.out.println(user.getVar());
val = 21;
System.out.println(user.getVar());
}
}
User class
public class User {
private Integer var;
public Integer getVar() {
return var;
}
public void setVar(Integer var) {
this.var = var;
}
public User(Integer var) {
this.var = var;
}
}
The thing I struggle to understand is why the value in User class doesn't change when we change its reference in Main class. How can we change a value in User class changing the reference of the object anyway? I clearly don't understand something crucial about passing an object by reference and I'll be really glad if someone clarifies this moment for me.
I want to use Constructor Overloading in my class and I also would like to have some final variables to define.
The structure I would like to have is this:
public class MyClass{
private final int variable;
public MyClass(){
/* some code and
other final variable declaration */
variable = 0;
}
public MyClass(int value){
this();
variable = value;
}
}
I would like to call this() to avoid to rewrite the code in my first constructor but I have already defined the final variable so this give a compilation error.
The most convenient solution I have in mind is to avoid the final keyword but of course it is the worst solution.
What can be the best way to define the variable in multiple constructors and avoid code repetitions?
You are almost there. Rewrite your constructors such way that your default constructor call the overloaded constructor with value 0.
public class MyClass {
private final int variable;
public MyClass() {
this(0);
}
public MyClass(int value) {
variable = value;
}
}
If you have small number variable then it is ok to use Telescoping Constructor pattern.
MyClass() { ... }
MyClass(int value1) { ... }
Pizza(int value1, int value2,int value3) { ... }
If there is multiple variable and instead of using method overloading you can use builder pattern so you can make all variable final and will build object gradually.
public class Employee {
private final int id;
private final String name;
private Employee(String name) {
super();
this.id = generateId();
this.name = name;
}
private int generateId() {
// Generate an id with some mechanism
int id = 0;
return id;
}
static public class Builder {
private int id;
private String name;
public Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Employee build() {
Employee emp = new Employee(name);
return emp;
}
}
}
You can not assign final variable in both constructors. If you want to keep the final variable and also want to set via constructor then one possibility that you will dedicate one constructor to set the final variable and also include common code functionality needed by the class. Then call this from another constructor like this(*finalVariableValue*);
I'm trying to share variables between methods in different classes, but I don't know if I'm doing this in the correct way. Basically when I wanna use the variables on method2 I have to "transport" them throught method1 to method2 from the Class A, just take a look at the example because I don't know how to explain this properly.
Is this the correct way to do it? Because sometimes I do this over an over through methods and it looks ugly.
Example:
public class A {
int var1, var2, var3;
B b = new B();
b.method1(var1, var2, var3);
}
public class B {
public void method1(int var1, int var2, int var3){
//doSomething
method2(var2, var3);
}
public void method2(int var2, int var3){
//doSomething
}
}
Btw, is there any community where code reviews are done? I'm pretty new to code and I'm afraid that I'm creating code that isn't effective.
Thanks for the help! :)
Use getters and setters to get variable of Class A from B as following..
public class A {
private int var1, var2, var3;
public int getVar1(){
return var1;
}
public void setVar1(int var1){
this.var1 = var1;
}
public int getVar2(){
return var2;
}
public void setVar2(int var2){
this.var2 = var2;
}
public int getVar3(){
return var3;
}
public void setVar3(int var3){
this.var3 = var3;
}
}
public class B{
// Use var 1 from class A as following
A a = new A();
int x = a.getVar1(); //x has the value of Var1 now
a.setVar1(2); // var1 in class A has value 2 now.
}
Use interfaces rather than directly call a method of another class.
public class A {
private InterfaceB interfaceB;
interfaceB.method1(var1, var2, var3);
}
public interface InterfaceB{
public void method1(int var1, int var2, int var3);
public void method2(int var2, int var3);
}
public class B implements InterfaceB{
#Override
public void method1(int var1, int var2, int var3){
//doSomething
method2(var2, var3);
}
#Override
public void method2(int var2, int var3){
//doSomething
}
}
You should read about encapsulation.
Passing 3 variables encapsulated in 1 object with appriopriate accessors sounds like a better option to me (at least the code looks a bit cleaner).
Also, think of creating a utility class with static methods if it makes sense of course - sometimes you do not need class member fields at all because there is no state to this class (Math class is an example) and static methods that return the result of some calculation/transformation is a better option.
On a side note I can recommend you considering "Program to an interfaces" principle. You can read the relevant section right on the top of this page.
In B class, you declare a instance of A class, variables in A class is public. when you can use variable in A class.
Here is my 2 cents...
public class Sample {
//Property of the class
private int valueA;
//method to do some operation
//that relies explicitly on a
//property of the class
public void doSomething(){
//valueA is over 9000!?
int valueA = valueA + 9000;
}
//Method that does something that does not explicitly
//rely on a property of the class
//could be called from this or another class
public int doSomeOperationWithSomething(int something){
return something++;
}
}
Another alternative would be to create a static "utility" class for your methods
public class Utils{
public static int doMagic(int var){
return var * var;
}
}
used like this,
int num = Utils.doMagic(9);
These come about when you have some code that does that one useful thing, but you just can't figure out where to put it.
More importantly, you will want to maintain proper "encapsulation" (Read about that) in your code. This means limiting access to variables by other classes and allowing access to only what is needed.
public class Website {
//No one should ever be able to
//access this variable directly
//So we set it a private
private String article;
//A reader should be able to get the aricle
public String getArticle(){
return article;
}
//The reader should never be able to set
//an aticle on the website only read it
//You can leave this part out or
//set the method to private as i did.
private void setArticle(String article){
this.article = article;
}
}
public class Reader {
//Reference to website
private Website website;
public Reader(){
...
//the user can read an article
website.getArticle();
// but this is not available to them
website.setArticle("Some text"); // results in ERROR
}
}
I'm kind of confused about the outputs.
This is the first program.
class A {
private int price;
private String name;
public int getPrice() {
return price;
}
public String getName() {
return name;
}
}
class B {
public static void main(String[] args) {
A a = new A();
System.out.println(a.getName());
System.out.println(a.getPrice());
}
}
This program compile without error. And the variables have values.
output -
null
0
Second program is,
class B {
public void value() {
int x;
System.out.println(x);
}
}
This program won't even compile.
B.java:4: error: variable x might not have been initialized
The question is why these variables act different? What is the reason.
This may be a very simple question. But kindly explain me.
Thanks.
Instance variables are declared inside a class. not within a method.
class A {
private int price; //instance variable
private String name; //instance variable
}
And instance variables always get a default value( integers 0, floating points 0.0, booleans false, String / references null).
Local variables are declared within a method.
class B {
public void value() {
int x; // local variable
}
}
Local variables must be initialized before use.
class B {
public void value() {
int x = 2; // initialize before use it.
System.out.println(x);
}
}
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);
}
}