AccessOverviewInstance and class variablesMethod variablesExample: a “Rabbit” classStatementsStatements must be in methods (or in constructors)Access from inside a classAccessing from outside a class, 1Accessing from outside a class, 2ResponsibilityLoss of controlprivate variables and methodsLevels of accessLevels of access, IIGetters and settersImmutable objectsThe EndJan 14, 2019AccessOverviewQuestions covered in this talk:How do we access fields and methods?Why have access restrictions?What can have access restrictions?How do we provide or restrict access?Instance and class variablesYou can declare variables within a classThese variables are called instance variables, or fieldsEvery object of that class has its own copy of those fieldsThe fields describe something about the objectYou can also declare static variables within a classThere is only one of each static variableA static variable is also called a class variableThe static variable describes something about the class as a wholeMethod variablesYou can declare variables within a method or within a constructorThese are called method variables, not fieldsMethod variables are basically used for computationMethod variables are strictly temporary, and are used only within that methodWhen a method returns (completes), all its variables are discardedExample: a “Rabbit” classclass Rabbit { static int population; // class variable (counts Rabbits) double hunger; //instance variable double fear; // instance variable double courage = 0.75; // instance variable void eat() { double temp; // method variable temp = courage * hunger; if (temp > fear) { System.out.println(“Eating!”); hunger = hunger - 1; } }}StatementsYou can declare variables inside a class or inside a method or a constructorYou can put statements (executable code) only within methods and constructors, not inside a classDeclarations with initializations are still declarations, not statementsStatements must be in methods(or in constructors) class Rabbit { double hunger; // OK--declaration double fear = 5.0; // OK--still a declaration hunger = 5.0; // illegal--assignment statement Rabbit ( ) { hunger = 5.0; // OK—statement in a constructor} void eat ( ) { hunger = hunger - 1; // OK—statement in a method} }Access from inside a classInside a class, you can access other fields and methods inside the class just by naming themExample:class Person { int age; void birthday( ) { age = age + 1; } void growOlder( ) { birthday( ); }}Equivalently, you can use the keyword this: void birthday( ) { this.age = this.age + 1; } void growOlder( ) { this.birthday( ); }Accessing from outside a class, 1Outside a class (from some other class) you access instance variables and methods byNaming the object you want to talk toPutting a dotNaming the variable or methodExample:// if NOT in class Person, say:if (john.age < 75) john.birthday();Inside the class, the keyword this means “this object”:if (this.age < 75) this.birthday(); // "this" may mean johnAccessing from outside a class, 2Outside a class (from some other class) you access class variables and methods byNaming the class you want to talk toPutting a dotNaming the variable or methodExamples: Person.population = Person.population + 1; x = Math.abs(y);ResponsibilityIn Java, objects are considered to be activeThey have behaviorsThey are responsible for their own dataData (variables) must be kept consistentExample: population should never be negativeIn order for a class or object to be responsible for its own data, it must keep control of that dataLoss of controlSuppose a Rabbit object, bugsBunny, has a variable named hungerInside the class, this method is fine: void eat ( ) { hunger = hunger - 1; }From outside the class, the following is legal: bugsBunny.hunger = bugsBunny.hunger - 1;But should we be allowed to “reach inside” a rabbit?The class needs to protect itself from errors in other classes (and from malicious behavior)private variables and methodsIf you declare a variable or method to be private, that variable or method can only be accessed from within the classprivate methods also make sense, e.g. digest()If you declare a variable or method to be public, then any code anywhere can access itTypically, a class or object has bothMethods for use by the rest of the programMethods and variables that it alone should controlLevels of accessprivate -- access only from within the class“package” -- access from within the class, or from any class in the same directory (“folder”)This is the default; there is no package keywordprotected -- access from within the class, or from within any subclass, or from any other class in the same directorypublic -- access from anywhere at allLevels of access, IITo make a variable or method visibleOnly within this class: privateFrom this class and its subclasses: not possibleFrom this class and its subclasses, and any other class in this directory: “package” (default)From this subclass and its subclasses, and any other classes in this directory: protectedFrom anywhere: publicGetters and settersOne way to control access is via getters and setters: class Rabbit { private double hunger; // getterpublic double getHunger() { return hunger;} // setterpublic void setHunger(double hunger) { this.hunger = hunger;}This seems silly, but it’s much safer and more flexibleImmutable objectsSuppose a Planet has a mass, and you want to be able to see its mass but not change it: class Planet { private long mass; // ConstructorPlanet(long mass) { this.mass = mass;} //getterlong getMass() { return mass;} // Notice there is no setter! }The
View Full Document