Reputation: 1052
Here is another dumb question from me.I just read that if you define any method with "public" access , you can use that method in any other class if both the classes are in the same package. I tried that in Eclipse but it is not working. here is my code
first class in package "nameless"
package nameless;
public class Practice {
public static int number;
public String name;
public int Setnumber(int a){
number=a;
return number;
}
public String Setname(String s){
name=s;
return name;
}
public static void main(String[] args){
int num;
String nam;
Practice obj= new Practice();
num=obj.Setnumber(797);
nam=obj.Setname("Srimanth");
System.out.println("The number and name are"+ num+" "+nam);
}
}
So in the above code Setname is defined as public. here is another code in same package
package nameless;
public class Mainclass{
public static void main(String args[]){
Mainclass obj= new Mainclass();
obj.Setname("Srimanth");
}
}
The above program giving me error saying "The method Setname(String) is undefined for the type Mainclass".
help me out please.
Note:I am new to java programming. explain your answers in detail. thank you.
Upvotes: 0
Views: 620
Reputation: 192
You can also do this:
public class Mainclass extends Practice {
public static void main(String args[]){
Mainclass obj= new Mainclass();
obj.Setname("Srimanth");
}
}
if you use the keyword extends ,the object from class Mainclass inherits the methods from Practice class.
Upvotes: 0
Reputation: 1746
Your Mainclass
has no method setName()
. You would have to write
Practice p = new Practice();
p.setName("Srimanth");
Upvotes: 0
Reputation: 85779
The error message is pretty clear: The method Setname(String) is undefined for the type Mainclass it means that Mainclass
class does not have a method with name SetName. Just define a method in Mainclass
with that name, or use Practice
class instead.
Defining the visibility for a method (access modifier) as public
doesn't allow you to access the method from other objects which are not in the appropriate class hierarchy. You must have an instance of the same class or sub class to access that.
Upvotes: 3
Reputation: 121998
You won't get an Apple from Orange Tree.
Mainclass
doesn't have the method you are calling. Only Practice
class have that method. Please define a one in Mainclass
as well to access it.
Note: Though it is legal ,returning from a setter is not a good practice.
Upvotes: 0
Reputation: 1530
Mainclass
class does not have a method with name SetName
so the error The method Setname(String) is undefined for the type Mainclass".
Upvotes: 1
Reputation: 5712
In Mainclass
there is no method named Setname
. So you can't access non exist method. If you want to access the Setname method you must have an instance from Practice class
Upvotes: 1