50 likes | 208 Views
SEEM3460 Tutorial. Java Keyword – static. static Variables. class XY { static int x; // class variable int y; // instance variable } XY xy1 = new XY(); XY xy2 = new XY (); XY.x , xy1.x, xy2.x all refer to same int using XY.y gives an error
E N D
SEEM3460 Tutorial Java Keyword – static
static Variables class XY { staticintx; // class variable inty;// instance variable } • XY xy1 = new XY(); • XY xy2 = newXY(); • XY.x, xy1.x, xy2.x all refer to same int • using XY.y gives an error • xy1.y and xy2.y refer to different int
static Methods class XY { staticintx() {…}; // class method inty() {…};// instance-bounded method } • XY xy1 = new XY(); • XY xy2 = newXY(); • XY.x(), xy1.x(), xy2.x() are the same • calling XY.y() gives an error • xy1.y() and xy2.y() calls the same methods but with different scopes (encapsulation) • keyword this can be used in y, but not x
static Classes (Advanced, FYI) class XY { staticclass X {…}; class Y {…}; } • X is a classnested in XY • X can be used like a normal class of the name XY.X • Y is a Inner class of Outer class XY • Y cannot be used without an instance of XY • each instance of Y must be attached to an instance of XY, the containing instance of XY can be referred by XY.this
Exercise • Based on CD create: • static double totalCost; • static CD mostExpensiveCD; • double Cost; // this already exists • static introundedTotalCost(); • introundedCost(); • Update the constructor for making use of the new variables