When accessing a function from another class in c++, we can write: classA::fct();
Is there an equivalent operator in java? If not, how can we access a function from another class in java?
When accessing a function from another class in c++, we can write: classA::fct();
Is there an equivalent operator in java? If not, how can we access a function from another class in java?
Well the ::
-operator (Scope Resolution Operator) in C++ allows you to resolve ambiguous calls/references to identifiers. However, in java there are no independent functions as all functions are actually methods (members) of a class. As such there are no need for this operator, have a look here for differences between Java and C++ classes.
I am guessing you are attempting to access a member (possibly static) of a class, in which case you'd use the .
-operator as exemplified in Mwesigye's answer or as follows:
public class AB {
public static void main(String[] args) {
B myB = new B();
myB.printA();
}
}
public class A {
public static int getInt() {
return 4;
}
}
public class B {
public void printA() {
System.out.println(A.getInt()); // output: 4
}
}
Here the .
-operator is used to access printA()
from the instantiated object myB
(instantiated from class B). It is also used to access the static method getInt()
whose implementation is tied to class A rather than any object of A. More info can be found here.
Take an example of a Class Student with methods what you call functions in c++ eg.
class Student{
//a non static method
public void getFees(){
//your logic
}
public static void deleteSubject(){
// your logic
}
}
class Club{
//create a new instance of student class
Student student = new Student();
public void printData(){
//access a non static method
student.getFees();
//accessing a static method
new Student().deleteSubject();
}
}
Hope this will help.