ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Access, Encapsulation, and Scope
    Java 2022. 2. 8. 20:46

    자바의 Access와 Scope개념에 대해 정리하였습니다.

     

     


    < What are Access and Scope? >

    As our Java programs begin to get bigger and we begin to have multiple Objects and Classes that interact with each other, the concepts of access and scope come into play.

     

    Access

    • The public and private keywords and how they relate to Classes, variables, constructors, and methods
    • The concept of encapsulation
    • Accessor methods, sometimes known as “getters
    • Mutator methods, sometimes known as “setters

    Scope

    • Local variables vs. instance variables
    • The this keyword

     

     


    < The public Keyword >

    public and private keywords are defining what parts of your code have access to other parts of your code.

    public this means that any part of our code can interact with them - even if that code is in a different class!


     

    • To declare something to be public, use the public keyword in the declaration statement.

     

    Example)

    public class Dog{
      public String name;
      public int age;
     
      public Dog(String input_name, int input_age){
        name = input_name;
        age = input_age;
      }
     
      public void speak() {
        System.out.println("Arf Arf! My name is " + name + " and I am a good dog!");
      }
    }

    : we have a public class, constructor, instance variables, and method.

    public class DogSchool{
      public void makeADog(){
        Dog cujo = new Dog("Cujo", 7);
        System.out.println(cujo.age);
        cujo.speak();
      }
    }

    : Any method of the DogSchool class could make a new Dog using the public Dog constructor, directly access that Dog’s instance variables, and directly use thatDog’s methods.

     

     


    < The private Keyword and Encapsulation >

    The private keyword means that you can only access those structures from elsewhere inside that same class.

    Usually Class's instance variable or method.

     

    Example)

    public class DogSchool{
      public void makeADog(){
        Dog cujo = new Dog("Cujo", 7);
        System.out.println(cujo.age);
        cujo.speak();
      }
    }

    Above the code, If age variable and speak( ) method are marked as private in the Dog class, the DogSchool class won’t be able to do that. 

     

     

    +. Encapsulation

    : Encapsulation is a technique used to keep implementation details hidden from other classes. Its aim is to create small bundles of logic.

     

    Example: Bank and CheckingAccount object.

    public class Bank{
      private CheckingAccount accountOne;
      private CheckingAccount accountTwo;
    
      public Bank(){
        accountOne = new CheckingAccount("Zeus", 100);
        accountTwo = new CheckingAccount("Hades", 200);
      }
    
      public static void main(String[] args){
        Bank bankOfGods = new Bank();
        System.out.println(bankOfGods.accountOne.name);
        bankOfGods.accountOne.addFunds(5);
        bankOfGods.accountOne.getInfo();
      }
    }
    public class CheckingAccount{
      private String name;
      private int balance;
    
      public CheckingAccount(String inputName, int inputBalance){
        name = inputName;
        balance = inputBalance;
      }
    
      private void addFunds(int fundsToAdd){
        balance += fundsToAdd;
      }
    
      private void getInfo(){
        System.out.println("This checking account belongs to " + name +". It has " + balance + " dollars in it.");
      }
    
      public static void main(String[] args){
      
      }
    }

    A Bank object doesn’t necessarily need to know the inner workings of a CheckingAccount object. It doesn’t need to know that the money is stored in a field named money, or that interest is added to an account by using a method named .addInterest(). In fact, if it had access to those fields or methods, it’s possible that someone using a Bank object could change things in a CheckingAccount without realizing it. By limiting access by using the private keyword, we are able to segment, or encapsulate, our code into individual units.

     

     


    < Accessor and Mutator Methods >

    If we want some other classes to have access to private instance variable, but we don't want those classes to know the exact variable name.

    To give other classes access to a private instance variable, use an accessor method (a.k.a getter method)
    To allow other classes to reset the value stored in private instance variables, use an mutator method (a.k.a setter method)

     

    • Accessor(getter)
      1. always be public

      2. have a return type that matches the type of the instance variable they're accessing.
    public class Dog{
      private String name;
      
      public String getName() {
        return name;
      }
    }

     

    • Mutator(setter)
      1. often void methods —  they don’t return anything, just reset the value.
      2. often have one parameter that is the same type as the variable they’re trying to change.
    public class Dog{
      private String name;
    
      public void setName(String newName) {
        name = newName;
      }
     
      public static void main(String[] args){
        Dog myDog = new Dog("Cujo");
        myDog.setName("Lassie");
      }
    }

     

     


    < Scope: Global and Local Variables >

    The scope of the variable also determines what parts of your code can access that variable.

    The scope  of a variable is determined by where the variable is declared => where : curly braces { }

     

    • Global Variable : if instance variables are declared inside a class but outside any methods or constructors, all methods and constructors are within the scope of that variable.
    class Dog{
      public String name;
      public int age;
      public int weight;
     
      public Dog(){
        name = "Winston";
        age = 8;
        weight = 30;
      }
     
      public void speak(){
        System.out.println("My name is " + name);
      }
    }

     

    • Local Variable : if we have a variable declared inside a method, that variable can only be used inside that method. The same is true for parameters.
    int[] myArray = {1, 2, 3, 4};
    for(int i = 0; i < myArray.length; i++){
      int sum = 0;
      sum += myArray[i];
    }
    
    System.out.println(sum);   //   ERROR!!

     

     


    < Scope: The this Keyword >

    When local variables is exist with the same name as instance variables, to access the instance variable and not the local variable, we should use the this keyword.

    When local variables is exist with the same name as instance variables, Java refers to the local variable name By Default.

    The this keyword is a reference to the current object.

     

    Example)

    // in constructor
    public Dog(String name){
      this.name = name;
    }
    
    // in setter
    public void setName(String name){
      this.name = name;
    }

    In constructor : "set this Dog‘s instance variable name equal to the variable passed into the constructor"

     

     


    < Using this With Methods >

    Also using with methods, this keyword is a reference to the current object.

     

    Example)

    public class Computer{
      public int brightness;
      public int volume;
     
      public void setBrightness(int inputBrightness){
        this.brightness = inputBrightness;
      }
     
      public void setVolume(int inputVolume){
        this.volume = inputvolume;
      }
     
      public void resetSettings(){
        this.setBrightness(0);
        this.setVolume(0);
      }
    }

    : Rather than create a new object, we use this as the object. What this means is that the object that calls resetSettings() will be used to call setBrightness(0) and setVolume(0).

     

     

    +. this can be used as a value for a parameter.

    public void pairWithOtherComputer(Computer other){
      // Code for method that uses the parameter other
    }
     
    public void setUpConnection(){
      this.pairWithOtherComputer(this);
    }

    : We use "this" to call the method and also pass "this" to the method so it can be used in that method.

     

     

     

    'Java' 카테고리의 다른 글

    Static Variables and Methods  (0) 2022.02.09
    Math Methods  (0) 2022.02.08
    String Methods  (0) 2022.02.07
    Loops  (0) 2022.02.07
    ArrayLists  (0) 2022.02.06

    댓글

Designed by Tistory.