0
Help needed for a Novice programmer. How can a method in a "upper" class call another method in an inner class?
I created a class that has some methods and another class in it. I'm trying to call one of the methods in the inner class from a method in the "upper" class. The method in the inner class returns set of values, and I will like to use these values in one of the method in the "upper" class. I'm new to programming and will like to explore my way of writting before using industry best practice. Confused but determined dude...
8 Antworten
+ 5
You mean you want calling methodB of this pseudo code, from the methodA:
class A {
methodA() {
/* call to methodB() */
}
class B {
methodB() {
}
}
You can distinguish 2 cases of access:
- to method B of class B ( need to method be static )
- or to method B of instance of class B ( need to create an instance )
In both case, you need to declare public your methodB...
+ 4
Yes, if your method is public, she can be access from exterior, but has right to read private variables of its class... The variables need only to be static to be access by a static method ^^
+ 2
Example of @Nathan use a setter and a getter, but you can design the method ( and the signature ) you want... Passing multiple values to a function/method is as simple as passing multiple arguments, just set the signature at your convenience:
public void my_multi_setter(int intarg, string sentence, ....)
Return multiple value ask a little more effort: you must encapsulate your differents values in a list, or an a object, as a function can return an unique type of variable/value...
0
@visph
would it still work if the variables in the class B are private, but are used my method B().
class B {
private String name;
private int age;
methodB() {
}
0
@Visph
please can you explain if this is possible, is so how? I'm sure you can't return a void method..
class B{
String Name;
int Age;
method void setB(String myName, int myAge){
this.Name = myName;
this.Age = myAge;
}
// trying to return set values in above method "setB"
method getB(){
return setB;
}
}
0
Typically, it would be done like this ..
(NOTE: some implementation details left out)
class Person
{
string Name;
int Age;
public:
void setName(string n) { Name = n; }
string getName() { return Name; }
}
then, you can create and access a Person from another class ...
class Group
{
Person Leader;
public:
string getLeaderName() { return Leader.getName(); }
}
0
@Nathan
Thanks for the reply, I'm aware the example you've given is possibly, but I was trying to pass multiple agruement of different variable type (String, int ) in the setMethod. Is it possible?
0
Hopefully with these answers, you've got it now. Any chance you can give us another example to review?