Case:1
class A
{
private int i=0;
public void display()
{
this.getValue();
}
private int getValue()
{
return i+2;
}
}
Case:2
class B
{
public void display()
{
int i=0;
this. getValue(i);
}
private int getValue(int i)
{
return i+2;
}
}
Does the declaration of "i" in both cases have any great
difference (other than the global access) whenever I call
display() ?
In this very case the effect is the same, but an instance of the class in the first snippet will occupy more memory.
Other than that in the first case it's a variable with the same address on each call and it retains the value, but in the second case it's not necessarily a variable with the same address - it is reallocated and reinitialized on each call.
Since you actually don't ever change i variable value you should declare it as const - this will give more clear code.
In first case i is a part of the object. When u create an object from class A, the object allocates memory for the variable "i". And it will remain until the object deleted.
But in the second way when you create the object from class B, there will be no memory allocation for the variable i. But only when you call the display function -in class B- memory variable "i" will be allocated temporarily. (When function's work is done all local variables will free)
In first case i exists outside of any method
In second case i exists only when display() method is called. If you want to give it persistence you can declare it as static.
Related
For example I'm having a class with three overloaded methods like this:
class MyClass
{
int sum(int i)
{
// Method implementation.
}
int sum(string x)
{
// Method implementation.
}
int sum(object o)
{
// Method implementation.
}
}
My question is when I call the sum method of MyClass by passing any value (integer, string or object) it should invoke only third method (with object type input parameter)
class MainClass
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.sum(10);
obj.sum("X")
}
}
You said "without type casting" but you can't, because you need some way to indicate to the compiler which version to call, and the runtime uses the type it sees to do that bit. Boxing the int as an object means the compiler will pick the object version
sum(1);//call int version
sum((object)1); //call object version
sum((string)(object)"1"); //call string version
sum((object)(int)(object)1); //call object version
First of all, let me say that if you sometimes want to call one version of the sum function when working with ints and sometimes want to call another, overloading probably isn't the right tool to use. Overloading works best when you are implementing conceptually the same operation for a number of different types, and you want the compiler to figure out automatically which function is the right one to call for each type; if you need more manual control over which function is called, you're probably better off using different names.
That said, if you're sure that this is what you want to do, you could implement the overloaded version for object in terms of another function in the public interface, as in:
class MyClass
{
int sum(int i)
{
// Method implementation.
}
int sum(string x)
{
// Method implementation.
}
int sum(object o)
{
sum_object(o);
}
int sum_object(object o)
{
// Method implementation for objects
}
}
Then, when you want to apply the object version to int and string objects, you just call sum_object directly instead.
I want to change the global variable in a function where a local variable of same is already present.
int x=10; //global variable
void fun1()
{
fun2(5);
}
void fun2(int x)
{
x=7; //here i want that this statement assigns the value 7 to the global x
}
Just qualify it with this. It's a pretty common pattern, particularly for constructors:
public class Player
{
private readonly string name;
public Player(string name)
{
this.name = name;
}
}
While I view it as acceptable if your parameter really is meant to be a new value for the field (potentially in a method which creates a new instance based on the current one and the new value for the single field, for example), I would try to avoid it in general, just from a readability perspective. Of course, the names of your private fields are an implementation detail, but when reading the code for the method, it's confusing to have two different concepts represented by the same variable name.
Rename the local parameter value.
Like Yuriy Vikulov said.
this.x for non-static variables
int x=10; //global variable
void fun1()
{
fun2(5);
}
void fun2(int lx)
{
x=7; //if you want 7
x=lx; //if you want the paramValue
}
this.x for non-static classes
NameClass.x for static variables
I have noticed a situation where there is a class (say: ClassA) with variable declarations and various methods. And in another class (say: Class B), there is a method(MethodofClassB()) with the return type of the method as ClassA.
so it is like:
Class A
{
variable i,j;
public int MethodA()
{
//some operation
}
}
Class B
{
variable x,y;
public static A MethodB()
{
//some operation
return obj;
}
}
1) I understand that MethodB() return an object of ClassA. Waty would be the use(the intention) of returning the object of ClassA
2) What is the reason for defining MethodB() as Public static. what would happen if static was not used for MethodB()
3)What would the returned objct look like. I mean if my method returned an integer, it would return some numerical value say '123' . If a method returns an object of a class, what would be in the returrned value.
please help me understand this with a small example
1) I understand that MethodB() return an object of ClassA. Waty would be the use(the intention) of returning the object of ClassA
Depends on what the method does, which isn't illustrated in this example. If the result of the operation is an instance of A then it stands to reason that it would return an instance of A, whatever A is.
For example, if A is a Car and B is a CarFactory then the method is likely producing a new Car. So it would return a Car that's been produced.
2) What is the reason for defining MethodB() as Public static. what would happen if static was not used for MethodB()
public allows it to be accessed by other objects. static means it's not associated with a particular instance of B. Both are subjective based, again, on the purpose of the method (which isn't defined in the example). Being static, it can be called as such:
var newInstance = B.MethodB();
If it wasn't static then an instance of B would be required:
var objectB = new B();
var newInstance = objectB.MethodB();
There are more and more implications here, including things like memory/resource usage and thread safety. All stemming from the purpose and business logic meaning of what B is and what MethodB does.
3)What would the returned objct look like. I mean if my method returned an integer, it would return some numerical value say '123' . If a method returns an object of a class, what would be in the returrned value.
It would be an instance of A. Similar to creating an instance here:
var objectA = new A();
This method also creates (or in some way gets) an instance:
var objectA = B.MethodB();
Without knowing more about what A is, what its constructor does, and what MethodB does, these two operations are otherwise the same.
First, your code is incorrect. There is no "ClassA" class. The class name is A, so the return type should be A not ClassA.
Second, the standard Java coding standards say to start methods and variables with lower case letters. So, your example should have been:
Class A
{
A anA;
B aB;
public int methodA()
{
//some operation
}
}
Class B
{
SomeType x, y;
public static A methodB()
{
//some operation
return obj;
}
}
David's answer shortly before mine is technically correct on points 1 and 2, although he also uses your mistake of calling the A type ClassA. His code for his answer to point 3, though, is incorrect and misleading. I would change his wording to this:
`3)What would the returned objct look like. I mean if my method returned an
integer, it would return some numerical value say '123' . If a method returns
an object of a class, what would be in the returrned value`.
It would be an instance of class A. Similar to creating an instance here:
A objectA = new A();
This method also creates (or in some way gets) an instance:
A objectA = B.methodB();
Without knowing more about what class A is, what its constructor does, and what methodB does, these two operations are otherwise the same.
I was wondering if which of the following patterns are considered to be more "correct".
The first example sets the value of private data member length by calling a void member function that implicitly takes arguments.
The second example sets the value of length by assigning it to the return value of the member function that explicitly takes an argument.
It seems that the second method makes the code clearer, since you know when and how the private member is getting set,
where the first requires a trace of the code to verify what and how a value is being assigned. The second method
also seems like it would allow for better reuse down the road because it could operate in any class/context (since the
arguments and return type are explicit).
The first method is quicker, and if used throughout the entire class (for private member functions) can save some coding, however I'm
not sure if this will bite me down the road ?
Thank you for the insight and clearing this up for me.
class MyDataType
{
private int length;
private string content;
private char[] buffer;
public MyDataType(str)
{
content = str;
calculateLength();
buffer = new char[length+1];
for(int i=0; i < length; i++)
buffer[i] = content[i];
buffer[i] = NULL;
}
private void calculateLength()
{
int i = 0;
while(content[i++] != NULL) {} // i know, buffer overflow...
length = i;
}
}
class MyDataType
{
private int length;
private string content;
private char[] buffer;
public MyDataType(str)
{
content = str;
length = calculateLength(content);
buffer = new char[length+1];
for(int i=0; i < length; i++)
buffer[i] = content[i];
buffer[i] = NULL;
}
private int calculateLength(string s)
{
int i = 0;
while(s[i++] != NULL) {}
return i;
}
}
In terms of readability and flexibility the second example wins out.
The advantage to using the second example is that you are essentially just delegating some work in the constructor to a method. This is easy to read and won't easily break in the future if, for instance, someone calls the private calculateLength() method without expecting the instance variables to change.
In the first example the calculateLength() method is operating on the member variables in a non-transparent way to the constructor which makes it less readable and more prone to be brittle in the way described above.
I would say the second is more appropriate, but the first works.
Usually getters are public, anywhere within a class you can access a private variable, doesn't make sense to have a getter that gets a private or protected variable in the same class. If it were protected and you could pass functionality to subclasses of your class.
It depends on what you want to do with the variable. If the value isn't going to change, I would just move the private calculateLength() method to the constructor. If you have to recalculate it then I guess I can see either the void or private doing pretty much the same thing. I feel that the second is clearer because you know exactly where the calculateLength() method is returning, but in the first it it is ambiguous to whether it is doing anything at all. It's better style to do the second.
Why not embed the getLength() function content into the constructor, and do the copying simultaneously? You will save yourself another loop.
Other than that, I am pretty sure it does not matter much. Just go with the flow, start with a method, and then modify in the future if you see fit.
What is the difference between a member variable and a local variable?
Are they the same?
A local variable is the variable you declare in a function.
A member variable is the variable you declare in a class definiton.
A member variable is a member of a type and belongs to that type's state. A local variable is not a member of a type and represents local storage rather than the state of an instance of a given type.
This is all very abstract, however. Here is a C# example:
class Program
{
static void Main()
{
// This is a local variable. Its lifespan
// is determined by lexical scope.
Foo foo;
}
}
class Foo
{
// This is a member variable - a new instance
// of this variable will be created for each
// new instance of Foo. The lifespan of this
// variable is equal to the lifespan of "this"
// instance of Foo.
int bar;
}
There are two kinds of member variable: instance and static.
An instance variable lasts as long as the instance of the class. There will be one copy of it per instance.
A static variable lasts as long as the class. There is one copy of it for the entire class.
A local variable is declared in a method and only lasts until the method returns:
public class Example {
private int _instanceVariable = 1;
private static int _staticvariable = 2;
public void Method() {
int localVariable = 3;
}
}
// Somewhere else
Example e = new Example();
// e._instanceVariable will be 1
// e._staticVariable will be 2
// localVariable does not exist
e.Method(); // While executing, localVariable exists
// Afterwards, it's gone
public class Foo
{
private int _FooInt; // I am a member variable
public void Bar()
{
int barInt; // I am a local variable
//Bar() can see barInt and _FooInt
}
public void Baz()
{
//Baz() can only see _FooInt
}
}
A local variable is the variable you declare in a function.Its lifespan is on that Function only.
A member variable is the variable you declare in a class definition.Its lifespan is inside that class only.It is Global Variable.It can be access by any function inside that same class.
Variables declared within a method are "local variables"
Variables declared within the class not within any methods are "member variables"(global variables).
Variables declared within the class not within any methods and defined as static are "class variables".
A member variable belongs to an object... something which has state. A local variable just belongs to the symbol table of whatever scope you are in. However, they will be represented in memory much the same as the computer has no notion of a class... it just sees bits which represent instructions. Local variables and member variables can both be on the stack or heap.