Search code examples
javaservletsmethod-signature

different signatures for accessing class methods


I really am a little confused here. Normal signature to call accessible class method or variable is (Class/Object).(method/variable). Then how do we give System.out.println()? Since System.out only gives the return type but does not belong to same class. Also in servlets, "this.getServletConfig().getInitParameter("defaultUser")" is not making sense to me, since getServletConfig() and getInitParameter are both member functions of same class, so signature becomes something like, class.method1().method2(), where method1 and method2 are member functions of same class. Can someone please explain..

Example:

Class CascMethodClassB() 
{ 
public CascMethodClassA methodTest()
{
    CascMethodClassA obj1 = new CascMethodClassA();
    return obj1;
}
} /*Class CascMethodClassB ends*/

Class CascMethodClassA() 
{
public int varTest;

public CascMethodClassA()
{
varTest = 7;
}

} /*Class CascMethodClassA ends*/


Class CascMethodClassC() 
{
CascMethodClassB obj2 = new CascMethodClassB();
int varTestC = obj2.methodTest().varTest

public static void main(String[] args)
{
System.out.println("varTest in CascMethodClassA is: "+ varTestC);

} /*Class CascMethodClassC ends*/

}

Thankyou, Fraggy.


Solution

  • Both are different cases.

    In the first case, outis a public static member in the System class. The member out is of type PrintStream, so the call

    System.out.println()
    

    will call the method println() from the PrintStream object (out).

    The second case, is something called method chaining. What happens is that class.method1() will return an object instance, according to Java docs it will return a ServetConfig object. So, you can again call a method from that returned object. Another way of seeing that call is (brackets are redundant, just there so you can visualize the order of the calls):

    (ClassName.someMethod1()).someMethod2();