Java Initialization/Declaration of Objects - java

I have an object, obj, of type MyObject, that I declare an instance of.
MyObject obj;
However, I don't initialize it. MyObject's Class looks something like:
public class MyObject {
public String i;
public String j;
public MyObject(String i) {
i = this.i;
}
}
So now, I want to set the value of j. So I say:
obj.j = "Hello";
Can I do this without having initialized obj? i.e. without saying:
obj = new MyObject("My i");
Will this object be null if I were to check the value of it, if I don't initialize it, or is setting a field within it enough to make it not null?
Thanks!

No, you cannot do that. You will have to create a new instance of MyObject if you want to access its fields.
Unless you make the fields static, ofcourse.
Do note that having your fields public violates encapsulation. You should make them private (or protected, if it's appropriate) and use getters and setters to provide access.
Sidenote:
public MyObject(String i) {
i = this.i;
}
This will not do what you want.
You have to assign the parameter i to the field variable i, not the other way around.
public MyObject(String i) {
this.i = i;
}

Related

How can I refer the objcet that calls a method in the method in Java? [duplicate]

This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
I'm trying to get an understanding of what the the java keyword this actually does.
I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
The keyword this can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: return this;
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
MyClass(String name)
{
this.name = name;
}
It can be used to invoke a different constructor of a a class from within a constructor:
MyClass()
{
this("default name");
}
It can be used to access enclosing instances from within a nested class:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
"this" is a reference to the current object.
See details here
The keyword this is a reference to the current object. It's best explained with the following piece of code:
public class MyClass {
public void testingThis()
{
// You can access the stuff below by
// using this (although this is not mandatory)
System.out.println(this.myInt);
System.out.println(this.myStringMethod());
// Will print out:
// 100
// Hello World
}
int myInt = 100;
string myStringMethod()
{
return "Hello World";
}
}
It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:
public class ProperExample {
private int numberOfExamples;
public ProperExample(int numberOfExamples)
{
this.numberOfExamples = numberOfExamples;
}
}
One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):
public class Square {
public Square()
{
this(0, 0);
}
public Square(int x_and_y)
{
this(x_and_y, x_and_y);
}
public Square(int x, int y)
{
// finally do something with x and y
}
}
This keyword works the same way in e.g. C#.
An even better use of this
public class Blah implements Foo {
public Foo getFoo() {
return this;
}
}
It allows you to specifically "this" object in the current context. Another example:
public class Blah {
public void process(Foo foo) {
foo.setBar(this);
}
}
How else could you do these operations.
"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.
Example ::
public class ThisDemo1
{
public static void main(String[] args)
{
A a1=new A(4,5);
}
}
class A
{
int num1;
int num2;
A(int num1)
{
this.num1=num1; //here "this" refers to instance variable num1.
//"this" avoids ambigutiy between local variable "num1" & instance variable "num1"
System.out.println("num1 :: "+(this.num1));
}
A(int num, int num2)
{
this(num); //here "this" calls 1 argument constructor within the same class.
this.num2=num2;
System.out.println("num2 :: "+(this.num2));
//Above line prints value of the instance variable num2.
}
}
The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.
Also, from 'this and super':
*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.
In fact, you can do anything with this that you could do with any other variable, except change its value.*
That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.
It's a reference of actual instance of a class inside a method of the same class.
coding
public class A{
int attr=10;
public int calc(){
return this.getA()+10;
}
/**
*get and set
**/
}//end class A
In calc() body, the software runs a method inside the object allocated currently.
How it's possible that the behaviour of the object can see itself? With the this keyword, exactly.
Really, the this keyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.
It can be also a way to access information on the current context.
For example:
public class OuterClass
{
public static void main(String[] args)
{
OuterClass oc = new OuterClass();
}
OuterClass()
{
InnerClass ic = new InnerClass(this);
}
class InnerClass
{
InnerClass(OuterClass oc)
{
System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
System.out.println("This class: " + this + " / " + this.getClass());
System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
System.out.println("Other way to parent: " + OuterClass.this);
}
}
}
Think of it in terms of english, "this object" is the object you currently have.
WindowMaker foo = new WindowMaker(this);
For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".
Every object can access a reference to itself with keyword this (sometimes called the this
reference).
First lets take a look on code
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
return this.name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
}
In the above method getName() return instance variable name.
Now lets take another look of similar code is
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
String name="Yasir Shabbir";
return name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
public static void main(String []args){
Employee e=new Employee();
e.setName("Programmer of UOS");
System.out.println(e.getName());
}
}
Output
Yasir Shabbir
this operator always work with instance variable(Belong to Object)
not any class variable(Belong to Class)
this always refer to class non static attribute not any other parameter or local variable.
this always use in non static method
this operator cannot work on static variable(Class variable)
**NOTE:**It’s often a logic error when a method contains a parameter or local variable that has the
same name as a field of the class. In this case, use reference this if you wish to access the
field of the class—otherwise, the method parameter or local variable will be referenced.
What 'this' does is very simply. It holds the reference of current
object.
This keyword holds the reference of instance of current class
This keyword can not be used inside static function or static blocks
This keyword can be used to access shadowed variable of instance
This keyword can be used to pass current object as parameter in function calls
This keyword can be used to create constructor chain
Source: http://javaandme.com/core-java/this-word

Enum static or non-static method

Consider the following enum class
public enum ClassA {
CHECK1("X", 0),
CHECK2("Y", 2),
CHECK3("Z", 1);
private final String id;
private final String cdValue;
private ClsA(String id, String cdValue) {
this.id = id;
this.cdValue = cdValue;
}
private String getId() {
return id;
}
private String getCdValue() {
return cdValue ;
}
private static final List<String> cdValues = new ArrayList<String>();
static {
for (ClassA clsA : ClassA.values()) {
cdValues.add(clsA.getCdValue());
}
}
public boolean isCdValue(String cdValue)
{
if clsValues.contains(cdValue)
return true;
else return false;
}
}
The question that I have is does the method isCdValue has to be static. I have to use this method isCdValue for every input given by the client. Therefore the method parameter cdValue changes for every input.
If it cannot be static then I would like to know how I can access this method. Please note I am primarily interested in learning about static of non-static method call. If it is a non-static call in a enum then how can we call this non static method. I am not trying to resolve the issue of how to get about checking the cdValue exists or not. It is just an example.
does the method isCdValue has to be static.
Yes, the method isCdValue has to be static here.
An enum is a special kind of class. An enum constant defines an instance of the enum type. An enum type has no instances other than those defined by its enum constants. Hence new can not be used to instantiate an enum.
An enum type has no instances other than those defined by its enum
constants. It is a compile-time error to attempt to explicitly
instantiate an enum type (§15.9.1).
Refer this
If you have to put the checking method in the Enum, I think it should be static
you can do this check:
ClassA.isCdValue(para)
Note that, you cannot new an Enum object. So if the method in your Enum, and it is not static, you cannot call it unless you have an Instance. but the goal of your method is checking if the string could be an instance.
another possibility is, use an immutable collection in your Enumm, and make it static and public. Then you could just call ClassA.CD_VALUES.contains(para)
If you want to access it from ClsA, you will have to make it static, if you want to access it from an instance of ClsSa then it doesn't.
A couple of other things: where do you declare clsValues in the first place?
There's no need for the complex if, you may replace this:
public boolean isCdValue(String cdValue)
{
if clsValues.contains(cdValue)
return true;
else return false;
}
with this
public boolean isCdValue(String cdValue){
return clsValues.contains(cdValue)
}
Last little thing, I'd strongly suggest you put curly braces around all your if and else's clauses, I've spent many a debugging hour because someone added a second line under the else, fooled by the indent and thinking it would only execute on the else.
You can use something like this, you do not need static List but the method has to be static as answered by Kent,
public static ClassA getClassAByCDValue(String cdValue)
{
for(ClassA value: ClassA.values())
{
if(value.cdValue.contains(cdValue))
{
return value;
}
}
return null;
}
public static boolean isCDValue(String cdValue)
{
for(ClassA value: ClassA.values())
{
if(value.cdValue.contains(cdValue))
{
return true;
}
}
return false;
}
Using above will be more appropriate as you just have to take care with adding/removing items in enum.

Access fields of an object passed as a parameter in Java?

Is it possible, in Java, to access fields of an object that is passed as a parameter in a method?
Example code:
void myMethod(ArrayList<Integer> list, MyClass object) {
Integer myInt = object.x; // x is an Integer-type field in the object
}
I tried the following:
MyClass curObj = (MyClass)object; to no avail.
Any suggestions?
When I use javac to compile, I get a cannot find symbol error.
If I understood the question correctly why simply not access object directly? e.g. if object had a member memberName and methodName() method, which are public, you could simply do
void myMethod(ArrayList<Integer> list, MyClass object) {
object.memberName = "member Name"
object.methodName();
}
You don't have to cast your 'object' as it is only object in name, you are getting passed a MyClass Object.
And by that I mean you are getting MyClass object not Object object
To access x like that make it sure it is public, BUT you should make an accessor method in MyClass:
public Integer getX()
{
return x;
}
and change your line to:
Integer myInt = object.getX();
No reasons it shouldn't work unless
object is null (but this would be a run-time, not compile-time error)
x is not public and myMethod is not a method of the MyClass class
Yes, it is possible if your attribute is declared as public. For example:
public class MyClass {
public int test;
}
class Test {
public printMyClass( MyClass c ) {
System.out.println( c.test );
}
}
Or you can have one method that returns test value and only MyClass can modify test attribute (better).
public class MyClass {
private int test;
public int getTest() {
return test;
}
}
class Test {
public printMyClass( MyClass c ) {
System.out.println( c.getTest() );
}
}
Only if MyClass.x is a public, then yes. Otherwise, you can reach it via that property's getter/setter methods. Java is actually passing a copy of the reference to the object, so while the called method is working only with the reference copy, the underlying object is the same whether you access it via a reference or a copy of the reference. The state of the object is also exposed for potential changes from within the called method.
Of course Your example code should work as is.
See that the field x has the word public in your MyClass.
//In MyClass
public Integer x;
If you don't declare it public you have to provide a getter method. This is the normal case (private + getter) JAVA Bean...
//In MyClass
private Integer x;
public Integer getX()
{
return x;
}
void myMethod(ArrayList<Integer> list, MyClass object) {
Integer myInt = object.getX(); // x is an Integer-type field in the object
}

Let a constructor access a static variable

Right now I have two .java files.
The Main.java:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger();
}
and the NeedInteger.java
public class NeedInteger {
System.out.println(integer);
}
This is of course very simplified, but is there any way I can accomplish this?
As many have answered, the correct method is to pass the value in to the constructor of the new class.
If for some reason you cannot do that, then you can use a public static accessor method in Main to access the value (this would be slightly better than just making the field public).
E.g.
public class Main
{
private static int integer = 15;
public static int getInteger()
{
return integer;
}
}
public class NeedInteger
{
public NeedInteger()
{
int integer = Main.getInteger();
}
}
Add a constructor to NeedInteger (and optionally a member if you need to also store it):
public class NeedInteger {
private int integer;
public NeedInteger(int integer) {
this.integer = integer;
System.out.println(integer);
}
}
Then pass your value when you create the instance:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger(integer);
}
You would have to do some bad juju moves (like using a global variable) or pass it to the constructor.
NOTE: your
public class NeedInteger {
System.out.println(integer);
}
has no method in it. I would recommend all this to be rewritten as such:
public Class NeedInteger {
NeedInteger(int integer) {
System.out.println(integer);
}
}
If you really want the work to be done on construction.
EDIT: From your comment above.
Instead, have the class structured so:
public Class NeedStringArray {
NeedStringArray(String[][][] stringArr) {
//work with String array here
}
}
That has no real additional overhead, since the actual array will not be passed, but only a reference to it. You WILL likely want to set the array to be final or something, to avoid it being edited in the NeedStringArray constructors.
integer is private, so it cannot be accessed by NeedInteger. you'll have to make it public or use a setter or getter and you'll need to use Main.integer since it's static.
Generally, you set in the Constructor.
Pass in the variable to the class constructor.
An array reference would be just that--a reference.
Or you could pass in the class itself, or use a static (meh).
Per your comment I'd say you can either host your array in a singleton
or as others suggested have the second class accept the reference to the array in the constructor. You can then use Dependency Injection framework (e.g. Guice) to get wire them up

How to use names to access variables in Java?

I am trying to write a method in a class which could be invoked several times, each time modifying one of the class' fields. However, I need to new the object and set the field's value to it if I want to modify it, but if do this inside the method, the reference seem to be lost and the field left unchanged after the calling.
Public class A {
private Immutable a; //Immutable class
private Immutable b;
public void modify(Immutable k,int v) {
k=new Immutable(v); //Now I am trying to pass
//a and b as parameters but they remain unchanged
}
}
Is there any way to pass the name of the field into the method (e.g., change the method modify(Immutable k, int v) to modify(String kName, int v), then use the name of the field to access it?
Thanks for any inputs!
Java does not support Call-by-name or call-by-reference, only Call-by-value. Your k variable (the method parameter) is completely independent from any variable used outside of the class (if there was one at all).
You could use Reflection to support passing "a" or "b" (or a Field object), but you should not.
Better have two methods:
public void setA(int v) {
this.a = new Immutable(v);
}
public void setB(int v) {
this.b = new Immutable(v);
}
If it is more complicated than a single constructor call, factor the common part out to a common method.
If you need to access a variable by a String key, you should use a Map.
Map<String, Immutable> _vars = new HashMap<String, Immutable>();
public void modify(String key, int v) {
_vars.put(key, new Immutable(v);
}
What I understand is that you're trying to create a new Immutable given an integer (v). In your modify method right now, k is a temporary reference. Setting the value "k =" in here, only affects the reference stored here in this method, not whatever reference you called modify with.
You have client code like this currently:
A a = new A();
Immutable k = new Immutable(x);
a.modify(k, y);
and you're hoping that k will be changed. What you really want instead of the 3rd line is:
k = new Immutable(y);
Assuming that things are really more complicated, then I would need more information to help you further.
Use a value holder.
public class ValueHolder<T> {
private T value ;
public ValueHolder(T value) {
this.value = value ;
}
public T get() {
return value ;
}
public void set(T value) {
this.value = value;
}
public static <V> ValueHolder<V> make(V value) {
return new ValueHolder<V>(value);
}
}
public class Processor {
private Inmutable a ;
private Inmutable b ;
public void modify(ValueHolder<Inmutable> k, int v) {
k.set(new Inmutable(v));
}
}
Once that is done you can get the instance you just created from the value holder.
Processor processor = new Processor();
ValueHolder<Inmutable> holder = ValueHolder.make(k);
processor.modify(holder, value);
k = holder.get() ;

Categories