different signatures for accessing class methods - java

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.

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();

System.out is a public class variable of type PrintStream, not a
method. Therefore you can invoke the println method on it, which returns void.
this.getServletConfig().getInitParameter("defaultUser") makes
perfect sense once you understand chaining method invocations. In
this case, you are:
calling the present instance of Servlet
getting its instance field's value of type ServletConfig
getting whichever String value is returned by invoking the getInitParameter method on the ServletConfig object
Finally, a method's signature is made of the method's name and parameter types

Each non-void method returns a type, which may be a different type to the declaring class, so the chained method/field will have the methods of the returned type (not the class it's called from or the class that the first method is defined in).
For example, to break down System.out.printkln():
System.out // out is a public field of type PrintStream
.println() // println() is a method of PrintStream, not System

Related

'this' parameter is being passed implicitly when a non-static/instance method is called - java

I read a statement that the keyword 'this' is being passed implicitly when a instance method calls another instance method of the same/another class.
Does it mean it look like:
class A {
void method1() {
this.method2(this);
// where 'this' is implicitly passed and the actual
// code looks like **this.method2();**
}
void method2() {
}
}
Are there any document that supports this statement? or a discussion in regards to this topic?
When you call a non-static method on an object:
object.method();
it is implicitly converted to
method(object);
and the value of object becomes this inside the method.

questions regarding the new keyword

I'm having difficulty understanding the concept of the new keyword. I know its used to instantiate objects; e.g. If I had a class called Superclass, I could create a object of that class by writing:
Superclass supeclassobject = new Superclass();
I understand that but what I dont understand is that this is also acceptable:
E.g. if your were passing a Superclass object to a method which takes it as an argument, then the following would still work:
public void MethodTakingSuperClassObjectAsArugment (new Superclass()){
*CODE HERE*
}
I cant understand how that works. You haven't given a name to the object so how could you refer to it in the method? This makes sense to me:
Superclass sobject = new Superclass();
public void MethodTakingSuperClassObjectAsArugment (sobject){
*CODE HERE*
}
You have a few misconceptions there.
First, there is a method definition, and then there is a method invocation.
Method definition is where you declare your method. You give it modifiers such as public/private/protected, a return type, a name, a list of parameters, an optional throws and a body:
public static int myInt( double myParameter ) {
return (int)myParameter;
}
Here, the parameters must have names. Otherwise, you would not be able to refer to them in the body.
And then there is the method invocation. Within some other method, like main, you call your method:
int a = myInt( 15.7 );
You passed 15.7 without giving it a name. The value that you actually pass in a method invocation is called an argument as opposed to a parameter, which is the formal name and type given in the method definition.
If your method definition included a parameter of the type SuperClass, it would look something like:
public static void myMethod( SuperClass myParameter ) {
...
}
You can't use new in a parameter declaration. But when you invoke the method, and you have to pass an argument to it, you can use:
myMethod( new SuperClass() );
In the same way that you didn't need to give a name to your 15.7 before, you don't need to give a name to your new object now. When Java passes it to the method, the method sees it as the value of myParameter.
Your second misconception is about names of objects. Objects don't actually have names. But they do have references. You can refer to an object from a local variable, from a field or from inside another object. In those cases, you give the reference a name, not the object. So you can do something like this:
Superclass myVar = new SuperClass();
Superclass anotherVar = myVar;
What you have here is two reference variables. You assign a reference to a new object to myVar. And then you assign a reference to the same object to anotherVar. Both myVar and anotherVar refer to the same object. The object does not have a name. You can now do something like myVar = null. But the object will still exist, and you'll be able to access it through anotherVar.
Think of reference variables as arrows. You give the arrow a name, and you can point the arrow at any object of the appropriate type. Or you can assign null to it which means the arrow is not pointing at anything.
Back to the issue of parameters, sometimes you can see something like this:
myMethod( new SuperClass() {
// Code here
} );
This is exactly the same as we did before. It's a method invocation. The code you see in the braces is not the code for myMethod. It is in fact the code for the new object. It's an anonymous class, which extends SuperClass, and has some of its own code in those braces. So the class is defined and an instance is created of it, and that instance - of an anonymous class extending SuperClass is what's being passed as an argument to myMethod. Inside myMethod, it can be accessed with myParameter. It's the same as writing this somewhere in the same file:
private class SomeClass extends SuperClass() {
// Code here
}
And then calling `myMethod` like this:
myMethod( new SomeClass() );

Passing parameter as Wrapper class and overriding

Please clarify my doubt on overriding, When I am calling a method which is not overrided, the method that is being called is form parent class, please give brief explanation on this, The example is like this
public class A {
public void test(int x){
System.out.println("Haiiiiiii");
}
}
public class B extends A{
public void test(Integer x){
System.out.println("hiii Im b's method");
}
}
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
B a=new B();
a.test(2);
}
}
I'm calling b's method but in B class the method takes wrapper class as parameter.
There are 2 methods. One accept int and other accept Integer type. So when you call test() method first it try to find a suitable method without doing any autoboxing. In that case it can find the parent class test() method which accept an int. Therefore java will execute that.
If in case it wouldn't exist then it will try to autobox your parameter and check if there a suitable method. In that case your child class method will get execute.
Edited
Java will always pick the most specific method for a type. Casting/autoboxing/unboxing only when it has to.
If you wanna call child class method you can try
a.test(new Integer(2));
In this case overriding not happen. since overloading when you call it will call the method accept input argument as int.
The compile lets you auto-box and unbox between primitives and wrappers but this doesn't make one a sub-class of the other. int and Integer are two different types hence both of them when used in the method act as two different method (as in your case)
Refer below link for a much clearer explanation
int does not override Integer in Java

Is it possible to call a method from another class with incorrect number of arguements in Java?

I have 2 java class as separate java files say, Class A and Class B
Class A had a method called Method A(1,2) with 2 parameters.
Class A(){
Method A(1,2)
}
Class B creates an object of Class A and try to access Method A with no parameters.
Class B(){
A a = new A()
a.Method A()
}
Is this case possible? If so how can I implement this in Java!
You can define a java method to accept any number of parameters using the "varargs" syntax, for example
public void myMethod(String... s) {
// s is an array String[]
}
If present, a varargs parameter must the last parameter.
These are all valid ways of calling this method:
myMethod(); // in this case the parameter is not null - it's an empty array
myMethod("foo");
myMethod("foo", "bar");
No you cannot call a method with the wrong number of parameters. In fact it shouldn't even compile. Either provide an overload with no parameters or provide default values.
Your option would be to send null values or string literals, or use String ... notation (if the arguments are strings).
Class A(){
Method A(){
return Method A(1,2);
}
Method A(1,2){
...
}
}
add a method with no parameters, which calls the 2 param method with default values.
hope it helps
You obviously can't call methodA() with no args on a classA reference, because classA simply doesn't have methodA() with no arguments.

question on the output of a java snippet

The following snippet gives output as
Sup.field=0, Sup.getField()=1
I do not understand why Sup.getField() does not get 0 instead?
class Super {
public int field = 0;
public int getField(){return field;}
}
class Sub extends Super {
public int field = 1;
public int getField() {return field;}
public int get SuperField() { return super.field;}
}
public class FieldAccess{
public static void main(String[] args){
Super Sup = new Sub();
System.out.println("Sup.field ="+Sup.field + ",Sup.getField()"+Sup.getField());
}
}
Instance variables are not overridden ..they are merely hidden. Referring to the super.field refers to the actual field in the super class based on reference.
Methods are overridden and the call is made based on the object type at runtime.
All methods in java are virtual (c# term) or polymorphic by default and that's what you are seeing (the class fields are not).
When you call sup.field, it accesses field field in class Super but when you call getField() it calls the getField() method in class Sub because the instance is of type Sub.
This page has a good definition and some examples of polymorphism.
This is because,
Super Sup = new Sub();
This means that the object holds instance of the derived class object. That means, in the object memory the value of field is 1 and not 0.
So, when you run
Sup.getfield()
it runs the method of the derived class which resides in the memory that is tagged as memory for the Super class.
So, Its the difference in what it is and what it seems like.
What you are witnessing is the effect of method overriding (not to be confused with method overloading).
Even though the reference type is of type Super(), the actual method to call is resolved when the program is executing (runtime polymorphism), and because the getField() method is overridden by the subclass, that is what gets called and hence returns the value in the subtype. If you want 0 in both cases, change your instantiation to Super Sup = new Sub();

Categories

Resources