Static vs Instance Flashcards

1
Q

Give me all scenarios involving static vs Instance method calls !

A

all scenarios involving calls between static and instance methods are :

  • A static member calling an instance member
  • A static member calling a static member
  • An instance member calling a static member
  • An instance member calling an instance member
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Give an example for each scenario (run the example) !

A

A static member calling another static member :

public class Static {
public static String name=”name”;
public static void first(){System.out.println(Static.name);} /* a static method calling a static variable using the classname /
public static void second(){Static.first();} /
a static method calling a static method using the classname */
public void third(){System.out.println(name);}
public static void main(String[] args) {
first();
second();
}
}

An instance member calling a static member :

public class Static{
public static String name=”name”;
public static void first(){
int r=Static.second(3,4); // An instance method calling a static method using the classname
System.out.println(r); }
public static int second(int a,int b){return a*b;}
public void third(){
int r=this.second(3,4); // An instance method calling a static method using a reference variable
System.out.println(r);
}
public static void main(String[] args) {
Static s=new Static();
s.third();
s.first();
}
}

An instance member calling an instance member :

public class Static{
public static String name=”name”;
public int number;
public void third(){
System.out.println(this.number); /* An instance method calling an instance variable using
a reference variable */
this.fourth(); // An instance method calling an instance method using a reference variable
}

public void fourth(){
System.out.println(“Fourth Method”);
}
public static void main(String[] args) {
Static s=new Static();
s.third();
}
}

A static member calling an instance member :

public class Gorilla {
public static int count;
public static void addGorilla() { count++; }
public void babyGorilla() { count++; }
public void announceBabies() {
addGorilla();
babyGorilla();
}
public static void announceBabiesToEveryone() {
addGorilla();
11 : babyGorilla(); // DOES NOT COMPILE
}
public int total;
14 : public static average = total / count; // DOES NOT COMPILE
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly