Author Topic:   Question related methods
Milind
ranch hand
posted March 16, 2000 08:12 AM             
Which statements on the <<< call >>> line are valid expressions?

public class SuperClass {

public int x;
int y;
public void m1( int a ) {
}

SuperClass( ) {
}
}

class SubClass extends SuperClass {

private float f;
void m2(int c) {
int x;
return;
}
SubClass() {
}
}

class T {

public static void main( String [] args) {
int i;
float g;
SubClass b = new SubClass( );
<<< calls >>>
}
}


A. b.m2();
B. g=b.f;
C. I=b.x;
D. I=b.y;
E. b.m1(6);
F. g=b.x;

A - Incorrect because the method m2() does not exist.
B - Incorrect because f is declared private.
C - Correct, declared public
D - Correct, , assuming that all the class files are in the same package.
E - Correct, valid method call.
F - Correct , same as C.

Please let me know if I am correct.
Thanks in advance !!
Milind

Tony Alicea
sheriff
posted March 16, 2000 08:29 AM             
I agree with all of yours except (minor):

It's not I but i, right?

C - Correct, declared public

Declared package access. The type of the reference is SubClass so the variable x is of that class.

eram
ranch hand
posted March 16, 2000 08:51 AM             
I think one cannaot call a superclass's method from an unrelated class with a subclass's instance.

b.m1(6) is invalid.

am i right or wrong ?

sree
ranch hand
posted March 16, 2000 09:13 AM             
Why is a incorrect. There is a method by name "m2" in the subclass. Am i missing something here?????

eram
ranch hand
posted March 16, 2000 09:17 AM             
m2() takes an argument.
b.m2(4) would be valid.

am i right ?

maha anna
bartender
posted March 16, 2000 09:28 AM             
eram,
As long as the unrelated class has access to any other class, it can create an instance of the class and through that instance, from that unrelated class , you can access any of the membors provided the members are accessible. The regular access rules apply here. So you have to re-check your statement. Do some testing in order to convice yourself when you get such doubts.

Sree,
See carefully. The method m2(int i) takes an int arg. There is no method as m2(). I think one important thing here is we have to double check our answers. Sometimes we miss the obvious.
regds
maha anna

sree
ranch hand
posted March 16, 2000 09:44 AM             
Bummer!!! Thanks Anna.

art
unregistered
posted March 16, 2000 09:58 AM           
If a method is defined in the base class and is not overridden in the subclass then it can be called by the instance of the subclass directly unless it is declared private in the base class? Can someone please clarify.

Tony Alicea
sheriff
posted March 16, 2000 11:02 AM             
You are correct art. But normal access modifiers apply. If the original method has "package access", then a subclass IN ANOTHER PKG cannot use it.

art
unregistered
posted March 16, 2000 11:22 AM           
Thanks Tony!

|