상세 컨텐츠

본문 제목

자바 실습 코딩(기본예제) pt.3 - object 등

CODING/Java

by 뚜뚜 DDUDDU 2022. 6. 1. 16:42

본문

package encap.bad;
public class MainClass {

	public static void main(String[] args) {

		MyBirth my = new MyBirth();
		my.year = -200084;
		my.month = 110;
		my.day = 13;
		my.birthInfo();  // 쓰레기값도 출력됨  --> 직접 year에 작성하지 못하게 하기 위해서 은닉을 써야 함
	}
}

package encap.bad;

public class MyBirth {

	int year;
	int month;
	int day;
	
	void birthInfo() {
		System.out.printf("내 생일은 %d년 %d월 %d일입니다.", this.year, this.month, this.day); //다른 객체의 각자 속성값이 다를 것이기 때문에 this를 붙임
	}
}

package encap.good;

public class MainClass {

	public static void main(String[] args) {

		MyBirth my = new MyBirth();
		
		my.setYear(2982);
		my.setMonth(4);
		my.setDay(13);
				
		System.out.printf("내 생일은 %d년 %d월 %d일 입니다.",my.getYear(), my.getMonth(), my.getDay("abc1234") );
	}
}
package encap.good;

public class MyBirth {

	/*
	 # 은닉(캡슐화) : 데이터 보호의 목적으로 사용하는 객체지향 기술의 하나.
	 - 은닉할 멤버변수에 private 제한자를 붙입니다.
	 */
	private int year;
	private int month;
	private int day;
	
	/*
	 - 은닉은 데이터에 제한을 걸어 정보 보호가 목적이지만, private를 설정하면 데이터 자체의 접근이 불가능해집니다.
	 - 따라서 데이터의 유효성을 검증할 수 있는 제어문을 사용하여 데이터 접근을 허용하도록 설정하는데, 이 때 사용하는 메서드를 
	 setter / getter 메서드라고 부릅니다.
	 
	 # setter method
	 1. setter는 은닉된 변수에 값을 저장하기 위한 메서드입니다.
	 2. 메서드 내부에 데이터 유효성 검증 로직을 작성하여 적절한 데이터만 멤버변수에 저장시키며, 
	 	접근제한자는 public으로 설정하여 외부에서 사용할 수 있게 합니다.
	 3. 메서드 이름은 일반적으로 set+멤버변수 이름으로 작성합니다.
	 */
	
	public void setDay(int day) {
		if(day < 1 || day > 31) {
			System.out.println("날짜를 잘못 입력하셨습니다.");
		}else {
			System.out.println("날짜가 정상 입력되었습니다.");
			this.day = day;
		}
	}
	
	/*
	 # getter method
	 1. getter 메서드는 은닉된 변수의 값을 참조할 때 사용하는 메서드입니다.
	 2. setter와 마찬가지로 public 접근제한자를 통해 외부에 메서드를 공개하고, 이름은 일반적으로 get9멤버변수 이름으로 지정합니다.
	 */
	
	public int getDay(String pw) {
		if(pw.equals("abc1234")) {
			return day;
		}else {
			System.out.println("비밀번호가 틀렸습니다.");
			return 0;
		}
	}
	
	/*
	 - month와 year의 setter/getter메서드를 선언하세요.
	 month: 1~12
	 year: 1900~3000 
	 
	 - getter는 비밀번호 없이 단순히 속성값을 리턴해 주세요.
	 */
	
	public void setMonth(int month) {
		if(month < 1 || month > 12) {
			System.out.println("월을 잘못 입력하셨습니다.");
		}else {
			System.out.println("월을 정상적으로 입력하였습니다.");
			this.month = month;
			
		}
	}
	public int getMonth() {
		return month;
	}
	
	public void setYear(int year) {
		if(year < 1900 || year > 3000 ) {
			System.out.println("년을 잘못 입력하셨습니다.");
		}else {
			System.out.println("년을 정상적으로 입력하였습니다.");
			this.year = year;
		}
	}
	public int getYear() {
		return year;
	}
}
package modi.protec.pac1;

public class A {

	protected int x;
	int y; //p.f
	
	protected A(int i) {}
	A(double d){}
	
	protected void method1() {}
	void method2() {}
	
	
}


package modi.protec.pac1;

public class B {

	A a1 = new A(30); //protected
	A a2 = new A(3.14); //p.f
	
	public B() {
		a1.x = 1;  //protec
		a2.y = 2;  //p.f
		
		a1.method1(); //protec
		a2.method2();
		
	}
	
}

package modi.protec.pac2;

import modi.protec.pac1.A;

public class C {
	
	A a1 = new A(30);  //protec
//	A a2 = newA(3.14);  p.f(x)

//	a1.x = 1;
//	a1.method1();
	
}


package modi.protec.pac2;

import modi.protec.pac1.*;

public class D extends A {

	/*
	 - protected 제한자는 패키지가 다른 경우에 두 클래스 사이에 상속관계가 있다면 super키워드를 통해 참조를 허용합니다.
	 */
	
	public D() {
		super(30);    //됨
//		super(3.5);  //p.f
		
		super.x = 1;
//		super.y = 2;  //p.f
		
		super.method1();
//		super.method2();  //p.f
		
		
		
		
	}
	
	
}
 
package obj_array;

public class Person {

	private String name;
	private int age;
	private String gender;  //알트 시프트 generate getters, setters 만들기
	
	public Person(String name, int age, String gender) {
		
		this.name = name;
		this.age = age;
		this.gender = gender;
		
	}
	
	public void personInfo() {
		System.out.printf("이름 %s, 나이: %d세, 성별: %s\n", this.name, this.age, this.gender);
	}
	
}
 
package obj_array;

import java.util.Arrays;

public class ArrayTest {

	public static void main(String[] args) {
		
		/*
		Person kim = new Person("김철수", 32, "남");
		Person choi = new Person("최영희", 25, "여");
		Person park = new Person("박길동", 45, "남");
		
		kim.personInfo();
		choi.personInfo();
		park.personInfo();
		*/
		
//		int[] arr = new int[5];
/*		Person[] people = new Person[3];
		people[0] = new Person("김철수", 32, "남");
		people[1] = new Person("최영희", 25, "여");
		people[2] = new Person("박길동", 45, "남");
		
		int[] arr = {1,3,5,7,9};  //이런방식으로도 넣을 수 있지 않을까?
*/		
		
		Person[] people = {
				new Person("김철수", 32, "남"),
				new Person("최영희", 25, "여"),
				new Person("박길동", 45, "남")
		};
		
		/*System.out.println(Arrays.toString(people)); (주소값)*/
		
/*		for(int i=0; i<people.length; i++) {
			people[i].personInfo();
		}*/
		
		for(Person p: people) {  //person 객체의 주소값을 받아줄 수 있는 타입: Person (이름: p)
			p.personInfo();
		}
	}
}



package obj_array;

import java.util.Scanner;

public class Arrayinsert {

	public static void main(String[] args) {

		/*
		 1. scanner로 이름, 나이, 성별을 입력받아서 입력받은 값을 토대로 Person객체를 생성하세요.
		 2. 객체를 3개 생성하신 후 반복문을 이용하여 그 객체의 personInfo 메서드를 호출하세요.
		 3. personInfo 메서드는 객체 3개가 모두 생성된 후에 출력하는 것으로 하겠습니다.

		 출력예시>
		 ***회원 정보 입력 ***
		 # 이름: 
		 # 나이: 
		 #성별: 
		 
		 ##정보 입력 성공 ###
		 **회원 정보 입력 ***
		 *
		 
		 ##정보 입력 성공 ###
		 
		 이름: xxx, 나이: ㅌㅌㅌ, 성별: xxx
		 이름: xxx, 나이: ㅌㅌㅌ, 성별: xxx
		 이름: xxx, 나이: ㅌㅌㅌ, 성별: xxx
		 
		 */
		
		Scanner  sc = new Scanner(System.in);
		Person[] people = new Person[3];
		
		for(int i=0; i<people.length; i++) {
			System.out.println("***회원 정보 입력***");
			
			System.out.print("# 이름: ");
			String name = sc.next();
			System.out.print("# 나이: ");
			int age = sc.nextInt();
			System.out.print("# 성별: ");
			String gender = sc.next();
			
			people[i] = new Person(name, age, gender);
			System.out.println("#정보 입력 성공");		
	}

		for(Person p : people) {
			p.personInfo();
		}
		
		sc.close();

	}
}


package obj_array;

public class test {

	private String name;
	private int age;
	private String gender;

	public void Person(String name, int age, String gender) {
		
		this.name = name;
		this.age = age;
		this.gender = gender;
	}
}
 
package poly.basic;

class A{}
class B extends A {}
class C extends A {}
class D extends B {}
class E extends C {}


public class Basic {

	A a = new A();
	B b = new B();
	C c = new C();
	D d = new D();
	E e = new E();
	
	/*
	 # 다형성이란 자식 객체가 모든 부모 타입을 사용할 수 있는 성질을 말합니다.
	 즉, 부모타입 변수에 자식 객체의 주소를 얼마든지 저장할 수 있다는 뜻입니다.
	 */
	
	A x1 = new B();  //B타입 --> B타입을 자동 형변환(promotion)
	A x2 = new C();
	A x3 = new D();
	A x4 = new E();
	
	B x6 = new D();
	C x7 = new E();
	
	/*상속관계가 없다면 다형성 적용이 불가능합니다.
	B x8 = new E(); (x)
	C x9 = new D(); (X)
	D x10 = new E(); (X)
	B x11 = new C();
	
	*/

	// Object는 최상위 타입입니다. 모든 클래스는 Object를 상속받습니다.
	
	Object o1 = new A();
	Object o2 = new B();
	Object o3 = new C();
	Object o4 = new D();
	Object o5 = new E();
	Object o6 = new Basic();
	Object o7 = new String("하이~");
	
	
	
	
}
 
package poly.car;

public class Car {

	Tire frontLeft;
	Tire frontRight;
	Tire rearLeft;
	Tire rearRight;  // 원래 KumhoTire를 Tire로 바꿔준다 
	
	
	public void run(){
		System.out.println("자동차가 달립니다");
	}
}
 
package poly.car;

public class Sonate extends Car {

	@Override
	public void run() {
		System.out.println("소나타가 달립니다~");
		
	}

}


package poly.car;

public class K5 extends Car {

	@Override
	public void run() {

		System.out.println("K5가 달립니다.");
	}

	
	
}


package poly.car;

public class Malibu extends Car {

	@Override
	public void run() {

		System.out.println("말리부가 달립니다~");
	}

}
package poly.car;

public class MainClass {

	public static void main(String[] args) {
		
		Sonate s1 = new Sonate();
		Sonate s2 = new Sonate();
		Sonate s3 = new Sonate();
		
		K5 k1 = new K5();
		Car k2 = new K5();  // car를 붙여도 괜찮음 is a 관계가 붙기때문에( 타입을 다 통일시켜 규격화 할 수 있다.
		K5 k3 = new K5();
		
		Malibu m1 = new Malibu();
		Malibu m2 = new Malibu();
		Malibu m3 = new Malibu();
		Malibu m4 = new Malibu();

//		s1.run();s2.run();s3.run();k1.run();k2.run();k3.run();m1.run();m2.run();m3.run();m4.run();  //원시적인 방법
		
/*		Sonate[] sonatas = {s1,s2,s3};
		for(Sonate s : sonatas) {
			s.run();
		}
		이것도 원시적인 방법
		*/
		
		Car[] cars = {s1,s2,s3,k1,k2,k3,m1,m2,m3,m4};
		for(Car c : cars) {
			c.run();
		}
		
		System.out.println("--------------------");
		System.out.println("# 타이어 교체 작업!!!");
		s1.frontLeft = new NexenTire();
		s1.frontRight = new NexenTire();
		s1.rearLeft = new NexenTire();
		
		
	}

}

package poly.car;

public class Tire {

}

package poly.car;

public class NexenTire extends Tire {

	public NexenTire() {
		System.out.println("넥센 타이어로 교체!");
	}
	
}



package poly.car;

public class KumhoTire extends Tire {

	public KumhoTire() {
		System.out.println("금호타이어로 교체!");
	}
}

관련글 더보기

댓글 영역