Method and Variable Name Is the Same

java instance variable and method having same name

Yes it's fine, mainly because, syntactically , they're used differently.

Why cant a function name and a variable name be called the same thing in a class?

Because in python the internal representation of class members is a dictionary __dict__ and it contains the names of all the methods and instance variables. And because the keys in the dictionary need to be unique they cannot be same. Essentially methods and variable share the same namespace (kind of read below)

To be precise __dict__ stores instance variables, only if a given key is not found it goes up to search class variables where the methods are stored also in a variable named __dict__.

So if you do:

class Employee:

def __init__(self, first, last):
self.first = first
self.last = last

def email(self):
return '{}.{}@email.com'.format(self.first, self.last)

def fullname(self):
return '{} {}'.format(self.first, self.last)

emp1 = Employee("John","Doe")
print(emp1.__dict__)

You will get {'first': 'John', 'last': 'Doe'}

So the search goes up to class varaibles:

 print(Employee.__dict__)

{'__module__': '__main__', '__init__': <function Employee.__init__ at 0x03933468>, 'email': <function Employee.email at 0x03933420>, 'fullname': <function Employee.fullname at 0x039333D8>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}

Where it finds the key email assigned to a function and invokes it.

But if your class contains that field:

class Employee:

def __init__(self, first, last):
self.first = first
self.last = last
self.email = "ple@ple.pl"

def email(self):
return '{}.{}@email.com'.format(self.first, self.last)

def fullname(self):
return '{} {}'.format(self.first, self.last)

print(emp1)
{'first': 'John', 'last': 'Doe', 'email': 'ple@ple.ple'}

And the search stops

As @Max pointed out there is a possibility to access the method if it has the same name. However,such practices should be avoided. I cannot think of an example where such a solution would be valid.

Can I use same name for public variable and method argument in java?

Yes you can.

The int number declared in the method is only accesible inside de method.

The int number declared as property in the class is accesible in any method for the class.

If you want to access to the number property inside the method, you must use this.

Example:

public static String function1(String id,int number)
{
this.number = number;
}

Is it okay to use the method's name for a variable in a method?

That variable isn't representing the average, it's representing the sum. You should name it that.

public static double average(double[] arr) {
double sum = 0.0;
for (int = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}

Can a variable and a method have the same name in C++?

Without discussing merits (or lack thereof), yes, you can disambiguate a member from a local variable rather easily.

bool const isBackendActive = this->isBackendActive();

or

bool const isBackendActive = Controller::isBackendActive();

Will work (and might as well be const correct).

Method and variable name is the same

Try this:

puts hello()

In Java, the variable name can be same with the classname

The compiler can tell by context. In the example you have given:

ClassName ClassName = new ClassName();
1 2 3

It can see that 1 is where a type name should be, so it knows you mean the class. Then, 2 is where a variable name is expected, so it knows that this should be the name of a variable. And 3 is coming after the new keyword with parentheses, so it must be the name of a class.

System.out.println( ClassName );

In this instance, ClassName is in the context of argument passing. A type name can't be passed as an argument, so you must mean the name of the variable.

To amuse yourself, you can change the print statement to:

System.out.println( ClassName.class );

Hover your mouse cursor on ClassName and you'll see that the compiler recognizes this as the name of a class. Then change it to:

System.out.println( ClassName.getClass() );

Hover your cursor again, and now you see that it recognizes it as the variable name. That's because .class can only be applied to a type name, while getClass() can only be applied to an object reference. The result of the print statement would be the same in both cases - but through different mechanisms.

So the compiler has no problem here. But you are right that it's not readable to humans. The convention is that names of variables and methods must start with a lowercase letter, while type names must start with an uppercase letter. Adhering to this convention will ensure that no such readability problems arise.

I can't say exactly why the authors of Java chose not to enforce this convention (that is, give a compiler error if type names started with a lowercase letter or variable/method names started with an uppercase), but I speculate that they didn't want to make anything an actual error unless it would actually cause an ambiguity for the compiler. Compilation errors are supposed to indicate a problem that makes the compiler unable to do its work.

Confusion over method parameter and instance variable having same name

Within a method, a method parameter takes precedence over an instance variable. The method modifyName refers to method parameter name, not the instance variable name.

Class method and variable with same name, compile error in C++ not in Java?

Because C++ is not Java. You can take the address of a member:

&Test::isVal

So you can't have two members have the same name, except that you can overload member functions. Even if you could disambiguate that by some kind of cast, the next problem would already arise at other places.

In C++, a lot of people including me usually call data members specially, like putting a m before their name. This avoids the problem:

class Test {
public:
bool IsVal() const { return mIsVal; }
private:
bool mIsVal;
};


Related Topics



Leave a reply



Submit