Can I use my instance variable as the contructor parameter? - java

class Myclass{
int x;
Myclass (int i){
x = i;
}
}
That is the code I have in my book. I wanted to know if this code would work?
class Myclass{
int x;
Myclass (x)
}
I also could try
class Myclass{
int x;
Myclass (int x)
}
in response to my first answer...would this work?

The latter code would not work because in Java you have to explicitly state the type. (There are no implicit type declarations)

You may have a parameter or local variable with the same name as an instance variable, yes. In that case, the parameter or local variable will shadow the instance variable. To refer to the instance variable in such a case, use:
this.x
For example, it's common to see this pattern:
class MyClass {
private int x;
public MyClass(int x) {
this.x = x;
}
}
Note that, as Josh M points out, it is not possible to omit the type. If that is what your question was about, then no, you may not.

This will compile:
class Myclass {
int x;
Myclass (int x) {
}
}
However, when you do this you end up with two variables with the same name, the instance variable x, which can be referred to explicitly inside the constructor (or any other class method) as this.x, and the local parameter variable x local to the constructor. If you just refer to x in the constructor you'll get the local one. This is referred to as variable shadowing.
Even though you've decided to give these two variables the same names in your source code, in the code the compiler produces they are completely unrelated. You might as well have named the parameter y.
An experiment to try that might help understanding this is to give the variables different types. Make your instance variable a boolean, for instance. Then you can try different things and see that they really are completely different variables that just happen to have the same name.

After #Chris Hayes' and #Samuel Edwin Ward's answers, here's one trick.
class MyClass {
private int x;
public MyClass(final int x) {
this.x = x;
}
}
The final modifier tells the compiler that that x cannot be modified. If you accidentally write
class MyClass {
private int x;
public MyClass(final int x) {
x = x; // Oopsie!
}
}
the compiler will complain.

Related

Why can't we define (assign a value) a variable (field) after it is declared in a class?

In a normal class,
public class MyClass {
int a =12;
}
works fine.
But,
public class MyClass {
int a =12;
int b;
b=13;
}
this gives a compilation error.
I know I am trying to access a field without using an object of that class, so I even tried this->
public class MyClass {
int a =12;
int b;
MyClass m= new MyClass();
m.b=13;
}
but even this doesn't seem to work.
I can accept the fact that this is how things work and move on. But does anyone know the logic behind this?
Thank you in advance.
int a = 12;
This is a variable declaration with initialisation.
b=13;
This is an assignment; a statement; it cannot be part of the declaration. It has to be part of the constructor or method.
It is how Java object definition works.
variable/field declarations
constructors
methods (static or non-static)
You can do it in one of the following two ways:
Use the initialization block as follows:
int b;
{
b = 13;
}
Do the following in the constructor:
b = 13;
Check https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html to learn more about it.

Why can I declare the datatype of a variable twice?

In the code below:
public class Square
{
private double side;
public Square(double a)
{
double side = a;
}
public double area()
{
return side * side;
}
public static void main(String[] args)
{
Square r = new Square(10.0);
System.out.println(r.area());
}
}
When the field is declared:
private double side;
and then in the constructor:
double side = a;
Why is an error not thrown?
I would think so because we are declaring the datatype of the variable double twice. Why does this code execute?
Because the second one declares a variable local to the constructor. It overshadows the member variable (which you can still access there via this.side).
In that context, that declaration is perfectly useless, as that variable will disappear as soon as the constructor ends.
Also, even if it was a problem, it wouldn't throw a runtime error. It would be a compile-time error.
Declaring a variable involves declaring its data type as well, so you are essentially asking about declaring the same variable twice.
You are right in assuming that declaring the same variable twice is not possible, but that's not happening in your code. Your
private double side;
is a data member of Square object, that is, a property of squares. It is declared in the block of the class definition, hence it's a data member.
Your
double side = a;
is a local variable defined in a method, which is the constructor in our case. It's legal syntactically, since it's not a member of Square and hence it has nothing to do with the member. Now, having said that I must mention that you have made a mistake, since inside the constructor you have declared a variable with the same name as your data member, initialized your local variable and then you never use it, while in another method you assume that side is initialized. So you have almost certainly intended to initialize your data member in your constructor, like:
public Square(double a)
{
this.side = a;
}
or even
public Square(double a)
{
side = a;
}

Make a group of variables public in java

Is there an easy way to make a group of variables in a class as public. For example to make a group of variables as static, I can use something like below.
class A {
static {
int x;
int y;
}
}
Is there a way to do something similar to make the variables as public. Something like this.
public {
int x;
int y;
}
Edit:
I understood that the static block doesn't do what I supposed it will do. What I need is a java version of something like this in C++
class A {
public:
int x;
int y;
}
Your code sample doesn't make a group of variables static, it declares local variables in a static initialization block.
You'll have to declare each variable as public separately.
The above code declares a static initialization block which is not same as declaring the variables as static. (More info.)
For the problem at hand you have to declare variables public separately.
You could use public int x,y. And be careful about static {} blocks.
static int x,y,z;
This should make a group of variables static... as long as they are of the same type of course. You can also make them all public, private etc.
public static int x,y,z;

Accessing a private variable through static method in java

Let say I have the following java classes:
Class A:
public class A {
private int x;
public A(int x){
this.x = x;
}
public static void main(String[] args) {
A a = new A(1);
B b = new B(1,2);
System.out.println((A)b.x);
}
}
Class B:
public class B extends A {
public int y;
public B(int x, int y){
super(x);
this.y = y;
}
}
Why does the compiler marks the access to x on this line
System.out.println((A)b.x);
as an error, even though I'm trying to access x from the class in which it is defined?
Is it because of:
1. the use of polymorphism?
2. the use of a static method?
3. the use of the main method?
You need to make it ((A)b).x to properly type cast it
Note : You are trying to type cast the property x to type A. That's the error!
int x is private therefore it can't be reached from outside of the scope of the class. You could mark it as protected. This way it will still have limited scope. Classes that extend A will be able to access the variable freely.
This is because the dot operator has precedence over the cast operator. This will work, because it forces the cast operator to be applied before the dot operator:
System.out.println(((A)b).x);
Demo on ideone.
When you write (A)b.x, the compiler try to cast b.x into A, but x is an int
Moreover, you don't need to cast b into A and you can't access b.x because x is a private field.
You may need a getter for this, like b.getX()
You have follwing issues
Compiler will show "Field not visible" Error,Because you trying to access private method of parent class
Syntactically. operator has precedence over cast operator
And another impotent thing is that No need to cast a child object to parent to access parent specific members, Because they are already inherited to the child, Here the member you are accessing is private ,which is not inherited. Even if you cast to parent you cant access private members using child object.
Because you are trying to cast an int into A. You need to wrap the cast around the object and then call .x.
Your call is equivalent to (A)(b.x), when it should be ((A)b).x.
public static void main(String[] args) {
A a = new A(1);
B b = new B(1,2);
System.out.println(((A)b).x);
}
Basically, two issues exist here.
One being that int x is private so it cannot be accessed from the sub-class.
Now even if you change the access criteria of int x to publicor protected; the code will still not work because (A)b.x will try to typecast an integer (read x) to an object (read A). Instead of this, you should use ((A)b).x

Java - when to use 'this' keyword [duplicate]

This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
What is the best practise for using the this keyword in Java? For example, I have the following class:
class Foo {
Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
}
That's fine and all, but Java is clever enough to know what is happening if I change the statement in the constructor to
bar = bar;
So why use the this keyword? (I realise in some situations, it's totally necessary to use it, I'm just asking for situations like this). Actually, I tend to use the keyword purely for readability sake but what's the common practise? Using it all over the shop makes my code look a bit messy, for example
boolean baz;
int someIndex = 5;
this.baz = this.bar.getSomeNumber() == this.someBarArray[this.someIndex].getSomeNumber();
Obviously a poor bit of code but it illustrates my example. Is it just down to personal preference in these cases?
but Java is clever enough to know what is happening if I change the statement in the constructor to
bar = bar;
FALSE! It compiles but it doesn't do what you think it does!
As to when to use it, a lot of it is personal preference. I like to use this in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.
As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
You should use it when you have a parameter with the same name as a field otherwise you will run into issues. It will compile, but won't necessarily do what you want it to.
As for everywhere else, don't use it unless it's needed for readability's sake. If you use it everywhere, 20% of your code will consist of the word 'this'!
this keyword refers to the Object of class on which some method is invoked.
For example:
public class Xyz {
public Xyz(Abc ob)
{
ob.show();
}
}
public class Abc {
int a = 10;
public Abc()
{
new Xyz(this);
}
public void show()
{
System.out.println("Value of a " + a);
}
public static void main(String s[])
{
new Abc();
}
}
Here in Abc() we are calling Xyz() which needs Object of Abc Class.. So we can pass this instead of new Abc(), because if we pass new Abc() here it will call itself again and again.
Also we use this to differentiate variables of class and local variables of method. e.g
class Abc {
int a;
void setValue(int a)
{
this.a = a;
}
}
Here this.a is refers to variable a of class Abc. Hence having same effect as you use new Abc().a;.
So you can say this refers to object of current class.
Actually
baz = baz
will raise this warning
The assignment to variable baz has no
effect
So what you think is wrong, the local scope overrides the class attribute so you MUST use this keyword explictly to assign the variable to the class attribute.
Otherwise the variable accounted into assignment is just the one passed as a parameter and the class one is ignored. That's why this is useful, it's not a fact of readability, it's a fact of explicitly deciding which baz are you talking about.
I would say
use this wherever not using it would cause ambiguities (or compiler warning, that are more important), otherwise just leave it. Since its purpose is exactly to solve ambiguities when default assumptions (first check locals, then check class attributes) are not enough.
It is common to use this keyword in explicit constructor invocation. You can see an example from the documentation.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
public Foo(Bar bar) {
this.bar = bar;
}
is not the same as
public Foo(Bar bar) {
bar = bar;
}
In the second case the bar in scope is the parameter, so you assign it to itself. this.bar remains null.
Depending on convention, you can use it for readability. It stresses the fact that it's an object variable.
I also like to have setter arguments with the same name as the variable (looks better in method signature). You need this in this case.
It is a personal preference - choose a style and stick to it. I personally use this but others think it is redundant.
Personal preference, but I use it to solve ambiguities only, and I suppose in the very rare case to make it obvious that the assigned variable is a field. There are some projects where people use "this.field" on every single field reference. I find this practice visually distracting to the point of being obnoxious, but you should be prepared to see such code once in a while.
I secretly think there's a special place in hell for people who write 500 line classes that have 275 'this' keywords in them, but this style is found in some open source projects, so to each his own I guess.
I always try to use this keyword on local class objects.
I use it to visually remind me if an object is static object or class object.
It helps me and the compiler differentiate between method args and local class object.
public void setValue(int value){
this.value = value;
}
It helps me to visually remind me if there is such a local object in an inner/nested/anonymous class to differentiate it from encapsulating class objects. Because if there is not this prefixed, my convention will remind me that it is an object of the encapsulating class
public class Hello{
public int value = 0;
public boolean modal = false;
public class Hellee{
public int value = 1;
public getValue(){
if (modal)
return 0;
return this.value;
}
}
}
void set(int real)
{
this.real = real;
}
here this is a keyword used when there is instance variable is same as the local variable.
another use of this is constructor overloading. it can call the constructor in a overloaded constructor.
Use it for Cloning objects (by passing reference of itself through a copy constructor).
Useful for object that inherits Cloneable.
public Foo implements Cloneable {
private String bar;
public Foo(Foo who) {
bar = who.bar;
}
public Object getClone() {
return new Foo(this); //Return new copy of self.
}
}

Categories

Resources