[Java/자바] Objects, Constructor, Final keyword

sbj·2023년 11월 25일

Java

목록 보기
3/15
post-thumbnail

Learning Objectives

  • I will review about Java’s Objects, Constructors, and the Final Keyword.
    • 자바의 Objets, Constructor, Final Keyword에 대해 복습한다.
  • I will resolve my queries and follow my logic through direct coding.
    • 내 논리대로, 내 궁금한 점들을 직접 코딩을 통해 해소한다.

1. Objects

Java objects are very similar to the objects we can observe in the real world. A cat, a lighter, a pen, or a car are all objects.
자바 오브젝트는 → 실제 세상과 비슷하다 (?). 고양이, 라이터, 펜, 차 모두 객체이다.

They are characterized by three features:
오브젝트는 3개의 기능을 갖는다.

  • Identity
    • such as a random ID number or an address in memory. 임의의 ID 번호나, 메모리 주소 등.
  • State
    • States are stored in fields that represent the individual characteristics of that object. 상태는 그 객체의 개별적 특성을 나타내는 필드에 저장된다.
  • Behavior
    • Exposed through methods that operate its internal state. 내부에서 작동하는 메소드를 통해 드러난다.

      Example
      the “shooting” behavior will change the state of the pistol from “8 bullets'' to “7 bullets” and so forth every time the player shoots with the gun.
      → “Shooting” 은 플레이어가 매회 총을 쏠 때마다 피스톨의 상태를 8 bullets → 7 bullets 으로 변경한다.

      The “reloading” behavior will bring back the pistol into the original “8 bullets'' state.

      → “reloading”은 피스톨을 원래의 8 bullets으로 돌려놓는다.


Properties of Java Objects

One can usually interact with an object through its methods. Through states and methods, the objects stay in control of how the world can use it.
객체의 메소드를 통해 객체와 상호작용할 수 있다.
States와 Methods를 통해, 객체는 외부에서 어떻게 사용될 지 통제된다.


Objects Example

Main Class

public class Main {
	public static void main(String[] args) {
		
		Car myCar1 = new Car();
		Car myCar2 = new Car();
		myCar1.drive();
		myCar2.brake();
		System.out.println(myCar1.make);
		System.out.println(myCar1.model);
		System.out.println(myCar1.model+" is "+myCar1.color);		
		
		System.out.println(myCar2.make);
		System.out.println(myCar2.model);		
		
		System.out.println(myCar1.Name);
		myCar1.want();
	}
}

Car Class

public class Car {
	
	String make = "Chervolet";
	String model = "Corvette";
	int year = 2020;
	String color = "blue";
	double price = 50000.00;
	String Name = "SU BEEN";
	
	void drive() {
		System.out.println("You drie the Car");
	}
	
	void brake() {
		System.out.println("You step on the brakes");
	}
	
	void want() {
		System.out.println("want to have a porsche");
	}
}

2. Constructor

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:
‘Constructor’(생성자) 는 객체를 초기화하는 데 사용된다. 생성자는 클래스의 객체가 생성될 때 호출되고, 객체 속성의 초기값을 세팅하는 데에 사용할 수 있다.

Main Class

public class Main {
	public static void main(String[] args) {

		Human human = new Human("Rick", 64, 60.0); 
		Human human2  = new Human("Su been",25,49.0);
		System.out.println(human.name);
//		Test3
//		Human human3 = new Human(human2.name, human2.age, human2.weight);
//		System.out.println("This is human2's name: " + human3.name);
		Human human3 = new Human(human2.getName(), human2.getAge(), human.getWeight());
		System.out.println("This is human2's name: " + human3.name);
		System.out.println("This is human1's weight: " + human.weight);
		System.out.println("This is human2's name: " + human2.name + ", and human's age: " + human.age);

		//Test1 => Can call different constructors in sysout at the same time.
		System.out.println(human2.name + " "+human.weight);
		human2.eat(); human.drink(); human.drive();
		}	
}

IFFY

  1. A question suddenly arose. Can we create a constructor that receives the information of human2 at the same time?
    갑자기 궁금한 게 생겼다. human2의 정보를 전달받는 생성자를 동시에 생성할 수 있는지?

The answer is very simple, just input the information of human2 into the parameters of human3.
아주 간단하다. → human3의 파라미터에 human2의 정보를 입력해주면 된다.

  • Human human3 = new Human(human2.name, human2.age, human2.weight);
  1. However, this approach is definitely not a good practice because it completely ignores Java's encapsulation.
    그런데 해당 방법은 절대 좋은 접근이 아니라는 점. Java의 encapsulation을 완전히 무시해버리는 거니까.
  2. It’s usually better to encapsulate the fields and use getters and setters to access and modify them.
    getters and setters 메소드를 사용해 encapsulate 해주는 것이 바람직하다.

You can display information from different constructors at the same time using Getters & Setters. I think I'm beginning to understand the importance of encapsulation.
Getters & Setters를 통해 각기 다른 생성자의 정보를 동시에 출력할 수 있다. 캡슐화의 중요성을 이제야 알 것 같다.

Human Class

public class Human {
	String name;
	int age;
	double weight;

	Human(String name, int age, double weight ){
		this.name = name;
		this.age = age;
		this.weight = weight;	
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	void eat() {
		System.out.println(this.name.toUpperCase()+ " is eating"); // Test2 => I tried to converting it to uppercase and it worked!
	}
	void drink() {
		System.out.println(this.name + " is drinking");
	}
	void drive() {
		System.out.println(this.name + " is driving");
	}
}

3. Final keyword

First of all, final is a non-access modifier applicable only to a variable, a method, or a class.
final은 변수, 메소드, 클래스에만 적용 가능한 비접근 제한자이다.

In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended.
Final 키워드는 변수, 메소드 클래스가 수정될 수 없음을 의미한다.

public class Main {

	public static void main(String[] args) {
		final double pi = 3.15159;
		pi = 4; // ❌ Error
		System.out.println(pi);
	}
}
profile
Strong men believe in cause and effect.

0개의 댓글