Calling a static variable or method Flashcards
Give me one characteristic of calling a static member in java !
When calling a static member in java, the compiler checks for the type of the reference instead of the object that the reference points to.
EXAMPLE :
class Parent {
static void staticMethod() {
System.out.println(“Parent static method”);
}
static void **anotherMethod()** { System.out.println("Parent another method"); } }
class Child extends Parent {
static void staticMethod() {
System.out.println(“Child static method”);
}
static void **test()** { System.out.println("test ok"); } }
Static Method Call with Reference Type :
Parent p = new Child();
p.staticMethod(); // This will call Parent.staticMethod()
p.test(); // This will cause a compile-time error
Give 2 examples for that and run them !
EXAMPLE 1 :
package Koala;
public class KoalaTester{
public static void main(String[] args){
5 : Koala k=new Koala();
6 : System.out.println(“The first print
is “+k.count); // k is a Koala
7 : k=null;
8 : System.out.println(“The second print is
(after putting k=null) “+k.count); // k is still a Koala
}
}
EXAMPLE 2 :
Koala.count = 4;
Koala koala1 = new Koala();
Koala koala2 = new Koala();
koala1.count = 6;
koala2.count = 5;
System.out.println(Koala.count); /* prints 5 there is only one static variable since it is static */
Give one pitfall you should avoid and an example for it (run the example) !
One pitfall you should avoid when dealing with static members in java, is to think that the compiler will throw a NullPointerException when trying to call a static member using a reference type that points to a null object
EXAMPLE :
package Koala;
public class KoalaTester{
public static void main(String[] args){
5 : Koala k=new Koala();
6 : System.out.println(“The first print
is “+k.count); // k is a Koala
7 : k=null;
8 : System.out.println(“The second print is
(after putting k=null) “+k.count); // k is still a Koala
}
}
Remember to look at the reference type for a variable when you see a static method or variable. The exam creators will try to trick you into thinking a NullPointerException is thrown because the variable happens to be null. Don’t be fooled!