public class zclass{
void print(char a){
System.out.println(a);
}
}
class ppp{
public static void main(String args[]){
zclass ab;
ab.print('c');
}
}
What is the problem in this programe it is in java?
// try this. i can see you are just beggining
NB: compile the two classess separatly. also make sure they are in the same folder
//your first class
public class ZClass
{
public void printChr(char val)
{
System.out.println(val);
}
}
/*your second class from which you access the printChr() method above thru an object. (If you Know what i mean...OOP)*/
class Ppp
{
public static void main (String args[])
{
ZClass obj = new ZClass();
obj.printChr('a');
}
}
Reply:You need to create an instance of the zclass, not just declare a variable of the class type.
You have:
zclass ab;
You should have:
zclass ab;
ab = new zclass();
Or, more compactly:
zclass ab = new zclass();
Once you have an instance of the class (an object), you can then call methods on it. The only way around this restriction is to have static methods, in which case you just need the class name and you can skip creating a real object.
There is usually more than one way to approach a programming problem. In this case, the other way is to make the print() method static, as mentioned above. This would be just as easy as the original fix.
Here is what you have for the print() method:
void print(char a){
System.out.println(a):
}
To make it static, all you have to do is put the "static" qualifier in front:
static void print(char a){
System.out.println(a);
}
This works becauase the print() method does not access any non-static object data. In fact, this method only operates on the input variable character, so it has no state dependency that would require an object.
Now you can call the print() method, even without an object. So, before you had:
zclass ab;
ab.print('c');
Now all you have to do is this:
zclass.print('c');
So, when do you use static methods? When you don't have any dependencies on instance data members, either directly or indirectly. That means that a static method can only access the parameters passed in to it and any static class data members (like constants, etc.). It also means that it can't call any other methods in the class unless they are also static.
I hope this helps!
Reply:?
cheap flowers
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment