-
4일차_메서드와 클래스 다시 정리 + 클래스와 메서드를 이용한 객체지향 프로그래밍 맛보기1학년/자바 공부 2022. 7. 27. 14:17
내용 : 메서드, 클래스
메서드
- 메서드란 무엇인가?모듈화로 인해 전체적인 코드의 가독성이 좋아지고 유지보수가 좋다.
- 어떤 특정한 작업을 수행하기 위한 명령문의 집합 ( 중복 코드의 반복적인 프로그래밍을 피할 수 있다 . )
- 메서드 작성 방법은?접근 제어자 : 해당 메소드에 접근할 수 있는 범위 명시예제
- 메소드 이름 : 호출을 위한 이름 명시
- class Car{ private int currentSpeed; private int accelerationTime; ... public void accelerate ( int speed, int second ){ System.out.println( second + "초간 속도를 시속" + speed +"(으)로 가속함"); ... } ... }
- 매개변수목록 : 호출 시 전달되는 인수의 값 저장
- 반환 타입 : 메소드가 전체 작업을 마치고 반환하는 데이터 타입
- 접근제어자 반환타입 메소드이름(매개변수목록) { }
- 메서드 호출 방법은?
예제객체참조변수이름.메소드이름(인수1,인수2,...);
- class Car{ private int currentSpeed; private int accelerationTime; ... public void accelerate ( int speed, int second ){ System.out.println( second + "초간 속도를 시속" + speed +"(으)로 가속함"); ... } public class method01{ public static void main(String[] args){ Car mycar = new Car(); myCar.accelerate(60,3); } }
- . ( 닷 )을 사용하여 호출 가능
클래스
- 절차지향 프로그래밍이란 무엇인가?반복되는 동작을 함수 및 void형식으로 모듈화하여 사용하는 방식.예를 들면 ‘책’이라는 자료형을 구현하고 책에 대한 함수를 구현하는 C같은 언어
- 구성요소는 함수
- 위에서부터 아래로 처리하는 시스템 동적 방식을 생각한 후 세부 모델 디자인.
- PP ( Procedural Programming ) .
- 객체지향 프로그래밍이란 무엇인가?필요한 속성의 객체를 설계하고 조립한다는 느낌?세가지 특성이 있는데 1. 캡슐화 , 2. 상속 , 3. 다형성이다
- 구성요소는 객체.
- OOP ( Object Oriented Programming ). 모든 데이터를 객체로 취급한다.
- 자바에서 클래스란 무엇인가?하나의 클래스를 가지고 여러 객체를 생성하여 사용한다필드 : 클래스에 포함된 변수예를 하나 들자면
- 클래스 > 차( Car ) 설계도 필드 > 차 종, 차가 만들어진 연도, 색, max speed 같은 특징 메소드 > 악셀, 브레이크 인스턴스 > 내 차, 친구차, 차3, 차4 = 자동차 인스턴스는 하나의 클래스에 있는 각자 다른 값의 필드와 메소드를 가진다
- 메소드 : 특정 명령문. 위에서 설명
- 클래스는 필드와 메소드로 구성된다.
- 객체를 만들기 위한 설계도 ( OOP )
- 클래스를 생성하는 방법예를 들면
- class Car { private String modelName; private int modelYear; private String color; private int maxSpeed; private int currentSpeed; Car(String modelName, int modelYear,Stirng color, int maxspeed){ this.modelNAme = modelName; this.modelYear = modelYear; this.color = color; this.maxSpeed = maxSpeed; this.currentSpeed = 0; } public String getMOdel() { return this.modelYear + "년식 " + this.modelName + " " + this.color; } } public class Methos02{ public static void main(String[] args) { Car mycar = new Car("아반떼",2022,"흰색",200); System.out.printlin(myCar.getModel()); } } }
- class 클래스 이름 { }
- 클래스의 생성자를 작성하는 방법자바에서 생성자 이름 = 클래스 이름
- 생성자는 반환값 없지만 void형으로 선언하지는 않는다
- 초기화를 위한 데이터를 인수로 전달받을 수 있다.
- 객체를 초기화 하는 방법이 여러 개 존재할 경우 하나의 클래스가 여러 개의 생성자를 가질 수 있다.
클래스이름( 인수1, 인수2, 인수3,...){}
Car(String modelName, int modelYear,Stirng color, int maxspeed){ this.modelNAme = modelName; this.modelYear = modelYear; this.color = color; this.maxSpeed = maxSpeed; this.currentSpeed = 0; }
- 생성자는 객체의 생성과 동시에 인스턴스 변수를 원하는 값으로 초기화 할 수 있는 생성자라고 부르는 메소드
- 클래스에 변수와 메서드를 작성하는 방법
또는class Car { private String modelName; private int modelYear; private String color; private int maxSpeed; private int currentSpeed; // Car 변수 작성 Car(String modelName, int modelYear,Stirng color, int maxspeed){ this.modelNAme = modelName; this.modelYear = modelYear; this.color = color; this.maxSpeed = maxSpeed; this.currentSpeed = 0; } // car클래스의 메서드작성 public String getMOdel() { return this.modelYear + "년식 " + this.modelName + " " + this.color; } } public class Method{ public static void main(String[] args) { // Car 클래스 호출 후 mycar인스턴스 생성. Car mycar = new Car("아반떼",2022,"흰색",200); // car 클래스의 getModel 메소드 호출 System.out.printlin(myCar.getModel()); } } }
- class Car{ private String modelName; private int modelYear; private String color; private int maxSpeed; private int currentSpeed; public String getModel() { System.out.println(modelYear + "년식 " + this.modelName + " " + this.color); } } public class Method{ public static void main(String[] args) { Car mycar; mycar = new Car(); mycar.modelName = "아반떼"; mycar.modelYear = 2022; mycar.color = " 노란색 " ; mycar.show(); }
- 객체 변수 입력 → 객체 변수에 클래스 대입 → 객체변수.클래스변수에 값 대입 → 클래스변수 값 저장됨
- 객체란 무엇인가?내가 mycar라는 객체를 만들고싶다 ? → 설계도(클래스)를 이용하여 조립
- 구현할 대상. 클래스에 의해 실체화 된 객체가 = 인스턴스
- 메서드에서 객체를 호출하는 방법
- public static void main(String[] args) { // Car 클래스 호출 후 mycar인스턴스(객체) 생성. Car mycar = new Car("아반떼",2022,"흰색",200); } }
Q1. 메서드 호출 시 "Hello, World!" 를 출력하는 메서드를 작성하세요.
package 튜토리얼; import javax.sound.sampled.SourceDataLine; class printhello{ static void print(){ //클래스 메소드 System.out.println("hello world"); } void print2(){ //인스턴스 메소드 System.out.println("hi instance!"); } } public class methodtest1 { public static void main(String[] args) { //인스턴스 생성x 호출가능 printhello.print(); //인스턴스 생성 후 호출 printhello hello = new printhello(); hello.print2(); } }
Q2. 메서드 정수 2개를 입력받아 합, 차, 곱, 몫을 출력하는 메서드를 작성하세요.
package 튜토리얼; import java.util.Scanner; class cal{ static int sum(int x, int y){ return x+y; } static int minus(int x, int y){ return x-y; } static int multi(int x, int y){ return x*y; } static int div(int x, int y){ return x/y; } } public class methodtest2 { public static void main(String[] args) { //x y 스캔받는 스캐너 만들기 Scanner input = new Scanner(System.in); //x y 스캔 int x = input.nextInt(); int y = input.nextInt(); //메서드 호출 후 결과값 출력 System.out.println(cal.sum(x,y)); System.out.println(cal.minus(x,y)); System.out.println(cal.multi(x,y)); System.out.println(cal.div(x,y)); } }
Q3. 클래스 학생의 이름, 나이, 학번, 학과 정보를 보유하고, 이를 출력하는 studentInfo(); 메서드를 보유한 클래스를 작성하고, main 메서드에서 이 메서드를 실행하세요 객체 생성 시 학생의 이름, 나이, 학번, 학과 정보를 생성자의 인자(parameter)에 전달해야합니다.
package 튜토리얼; import java.util.Scanner; class student{ static String name; static int age; static int num; static String major; student(String inputname, int inputage, int inputnum, String inputmajor){ this.name = inputname; this.age = inputage; this.num = inputnum; this.major = inputmajor; } public String studentInfo(){ return "이름 : " + this.name + " / 나이 : " + this.age + " / 학번 : " + this.num + " / 학과 : " + this.major; } } public class methodtest3 { public static void main(String[] args) { //스캐너 만들기 Scanner input = new Scanner(System.in); //클래스 호출 student info1 = new student(input.next(),input.nextInt(),input.nextInt(),input.next()); //클래스의 메서드 호출 System.out.println(info1.studentInfo()); } }
728x90'1학년 > 자바 공부' 카테고리의 다른 글
8일차_클래스의 상속, 오버라이딩 + 실습 (0) 2022.08.23 6일차_클래스,메서드,랜덤 클래스를 활용한 자동차 프로그램 코드 (0) 2022.08.02 4일차_배열, 문자열, Int class , 아스키코드 (0) 2022.07.27 3일차_별찍기 3문제 (2) 2022.07.06 3일차_클래스의구성,생성자,메소드 (0) 2022.07.06