[Java/자바] variable scope, overladed constructors

sbj·2023년 11월 25일

Java

목록 보기
4/15
post-thumbnail

Learning Objectives

  • Review the basics of Java.

Variable scope

Global variables

A variable that is specified outside the function or block of the code is known as Global Variable.
Global Variables(전역변수)는 함수, 코드 블록 외부에 지정되는 변수이다.

Advantages. Why we use Global Variables?

  1. The global variable can be accessed from all functions or modules in a programme.
    프로그램 내 모든 함수에서 접근 가능하다.
  2. We only need to declare a single-time global variable outside the modules.
    모듈 밖에서 한 번만 정의해주면 된다.
  3. It is used when the user needs to access the same data all over the program again and again.
    프로그램 전체에서 동일한 데이터에 계속 접근해야 할 때 사용한다.

Disadvantages of using Global Variables

  1. So many variables are declared global, then they stay in memory until the execution of the program is completed. This can trigger the issue of Out of Memory.
    메모리 성능 저하 우려 → 전역변수는 프로그램 실행이 완료될 때 까지 메모리에 유지된다. 메모리 성능 저하를 유발할 수도 있다.

    I thought global variables were more convenient, but now I understand their disadvantages.
    단순히 전역변수가 더 편리하다고 생각했는데, 메모리 성능 저하라는 치명적 단점이 존재한다.

  2. We need to modify all the modules where they are named if global variables are discontinued due to code refactoring.
    코드 리팩토링으로 전역변수가 중단되면, 모든 모듈을 수정해줘야 한다는 점.

The worst fear of a developer is to have a program where a change in a single function causes a totally different part of the program to fail. Each global variable increases this risk.
개발자의 가장 큰 공포…...(?) 단 한 가지 기능 수정으로 인해 전체 프로그램이 중단되는 것. Global variable은 이런 위험을 증가시킴.


Global variables example

DiceRoller Class

public class DiceRoller {
	//Global variables -> declared outside a method, but within a class visible to all parts of a class
	Random random; 
	int number;
	
	DiceRoller(){
		random = new Random();
		roll();
	}
	void roll() {
		number = random.nextInt(6)+1;
		System.out.println(number);
	}
}

Main Class

public class Main {
	public static void main(String[] args) {
		DiceRoller diceRoller = new DiceRoller();
	}
}
  • Random random
    • Generate Random number.
      랜덤한 숫자를 생성한다.
    • it is accessible to all methods within the class.
      클래스 내의 모든 메소드에서 접근 가능하다 ⇒ Global variables.
  • int number
    • It’s also accessible to all methods in the class.
      마찬가지로, 클래스 내의 모든 메소드에서 접근 가능하다. ⇒ Global variables.
  • DiceRoller()
    • Constructor → initialize the ‘random’ variable by creating a new instance of the Random class. It has own random number generator.
      Random 클래스 내에서 새로운 인스턴스를 생성한다. random= new Random(); 로 자체적으로 랜덤 난수를 생성할 수 있다.
    • You then call the roll() method, which generates a random number and assigns it to the number variable.
      roll() 메소드를 호출하면, 랜덤한 숫자가 생성 → number 변수에 값을 저장한다.

Local variable

The Local Variable is specified in the programming block or subroutines as a form of variable declared. The local variable persists before the function's block is executed. It will be lost automatically after that.
코드블록이나 서브쿼리 내에 선언된 변수이다. local 변수는 함수가 실행되기 전 지속되고, 함수 종료되면 소멸된다.

Advantages. Why we use Local Variables?

  1. The variables' values stay unchanged while the task is running is the basic meaning of the Local variable.
    작업이 실행되는 동안 변수값은 변하지 않는다.
  2. If a single variable that is running concurrently is changed by many tasks, then the outcome can be unpredictable. However, declaring it as a local variable will solve it.
    동시에 실행되는 single 변수가 다수 작업에 의해 변경될 경우 → 결과 예측 불가능하다. 그러나 local 변수로 선언하면 해결할 수 있다. ⇒ 해당 작업에 종속되는 변수니까.

Disadvantages of using Local Variables

  1. A local variable's debugging method is very tricky.
    local 변수의 디버깅은 매우 까다롭다. → 왜?
  2. Popular data needed to be transmitted regularly as data sharing between modules is not feasible.
    데이터 공유가 불가능하므로, 정기적으로 전송해줘야 한다.
  3. They have a spectrum that is very small.
    스펙트럼이 좁다는 점.

❓ IFFY
Then, I started to wonder, in which situations is it most appropriate to use global variables and local variables?
그럼, 전역변수와 로컬 변수를 어떤 상황에 사용하는 것이 가장 적절한지가 궁금해졌다.

”If u are not sharing data with other function then you will use local variables to store the data.
If u are sharing data with other functions then you should go with global variables.”

When I need to share data with other then Global would be great, If not, use local. It’s a simple answer, but it clarifies their uses.
데이터 공유가 필요한 경우 Global, 아닐 경우 Local. 심플한 답변이지만, 용도를 알겠다.


Local variables Example

Main

public class Test {

	public void pupAge() {
		// age = local variable. This is defined inside pupAge() method and its scope is limited to only this method.
		int age = 0;
		age = age + 7;
		System.out.println("Puppy age is: " + age);
	}
	public static void main(String[] args) {
		Test test = new Test();
		test.pupAge();
	}
}

Overloaded Constructor

Main

public class Main {
	public static void main(String[] args) {
	
		Pizza pizza = new Pizza(); // Instance of Pizze class -> Create pizza
	
		System.out.println("Here are the ingredients of your pizza: ");
		System.out.println(pizza.bread);
		System.out.println(pizza.sauce);
		System.out.println(pizza.cheese);
		System.out.println(pizza.topping);
	}
}

Summary of the Lecture Code.
강의 코드 정리

Main

public class Main {
	public static void main(String[] args) {
	
		Pizza pizza = new Pizza(); // Instance of Pizze class -> Create pizza
	
		System.out.println("Here are the ingredients of your pizza: ");
		System.out.println(pizza.bread);
		System.out.println(pizza.sauce);
		System.out.println(pizza.cheese);
		System.out.println(pizza.topping);
	}
}

Pizza

public class Pizza {
	//Some of the value we receive
	String bread;
	String sauce;
	String cheese;
	String topping;

	//Pizza Constructor
	Pizza(String bread, String sauce, String cheese, String topping){ // 4 Parameters
		this.bread = bread;
		this.sauce = sauce;
		this.cheese = cheese;
		this.topping = topping;
	}
	Pizza(String bread, String sauce, String cheese){ // 3 Parameters
		this.bread = bread;
		this.sauce = sauce;
		this.cheese = cheese;
	}
	Pizza(String bread, String sauce){ // 2 Parameters
		this.bread = bread;
		this.sauce = sauce;
	}
	Pizza(String bread){ // 1 Parameters
		this.bread = bread;
	}
	Pizza(){ // 0 Parameters
	}
}

Aren’t there better solutions?
더 좋은 방법이 없을까? → Getters & Setters를 사용한다.

Why?

  1. Encapsulation
    캡슐화 → OOP의 기초. 데이터와 메소드가 각 클래스의 단위에서 작동하도록 한다. 또한, 구현 세부사항을 숨기고 데이터를 보호할 수도 있다.
  2. Flexibility and Maintenance
    유연성과 유지보수 용이
  3. Readability and Documentation
    가독성, 문서화에 용이하다.
    It's easy to understand what I'm getting and setting, even for me who wrote the code. (The below code is a little subpar.)
    내가 뭘 Get, Set..하는지 쓴 내가봐도 알기 쉽다. (하기 코드는 좀 별로지만)

Using getters & setters

public class Pizza2 {
	private String bread = "Plain";
	
	public String getBread() {
		return bread;
	}
	public void setBread(String bread) {
		this.bread = bread;
	}		
}
public class Main {
	public static void main(String[] args) {

		//getters & setters
		Pizza2 pizza2 = new Pizza2();
		System.out.println(pizza2.getBread());
	}
}
profile
Strong men believe in cause and effect.

0개의 댓글