















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Cannot make a static reference to the non- static field loc. Ewan Klein. Object-Oriented Programming: Static Methods & Variables ...
Typology: Schemes and Mind Maps
1 / 23
This page cannot be seen from the preview
Don't miss anything!
















......
Ewan Klein
Inf1 :: 2008/
...... ..^1.^ Static Methods ..^2.^ Static Variables ..^3.^ Admin
......
..^2.^ You’ve already seen them.
......
..^2.^ You’ve already seen them.
Calling a method from Maths
..
.
...
int randomNum = (int)( Math.random() * 5)
......
All ‘regular’ methods are non-static. A static method can be run without instantiating the class. Also called class methods. .Calling a Static Method .. .
...
Math.max(7, 22);. . Calling a Non-Static Method .. .
...
Cell c = new Cell(); c.move(6);
......
Classes with static methods often not meant to be instantiated. How to stop instantiation? ..^1.^ Make the class abstract. ..^2.^ Make the constructor private. .Private Constructor ..
public class Sim { private Sim() { } }
......
.Static Method in.^ Sim
public static Sim getInstance() { if (instance == null) { instance = new Sim(); } return instance; } . Calling the Method ..
public class AnimalCell extends BaseCell { Sim world = Sim.getInstance(); ... }
......
Classes with static methods may be instantiated. And static and non-static methods can be mixed. . .Mixed methods.
public class Cell1 { public static void main(String[] args) { Cell1 c = new Cell1(); c.hello(); } public String hello() { return ”I’m a cell!”; } }
......
A static method cannot use an instance variable. Think about it. .Mixed methods ..
public class Cell int loc = 0; public static void main(String[] args) System.out.println(”I’m at: ” + loc ); // Wrong! public int getLoc() return loc ; // OK
......
Output ..
Exception in thread ”main” java.lang.Error: Unresolved com- pilation problem: Cannot make a static reference to the non- static field loc
......
.Does Work.
public class Cell3 { int loc = 0; public static void main(String[] args) { Cell3 c = new Cell3(); System.out.println(”I’m at: ” + c.getLoc()); } public int getLoc() { return loc; } }
......
Static variable: one value per class, not one value per instance. Also called: static field, class variable
......
.How many prints?
...
public class Lithograph { static int printsMade = 0; private int copyNo; public static void main(String[] args) { ArrayList
......
.Output ..
Copy 1 of 6 Copy 2 of 6 Copy 3 of 6 Copy 4 of 6 Copy 5 of 6 Copy 6 of 6