///////
Search

07_클래스와 객체(1)_이연재

7장 클래스와 객체

절차 지향 언어: c언어
객체 지향 언어: java
객체 지향 언어의 특징으로 캡슐화, 상속, 추상화, 정보 은닉등이 있다.
함수형 언어

1.클래스

클래스 안에는 변수와 메소드가 들어간다.
클래스 이름의 첫글자는 대문자로 만들어야 한다.(켐멜 표기법,_지양하기)
public class Circle{ int radius; string color; double calcArea(){ return Math.PI * radius * radius; } }
public: 접근 지정자
radius, color: 변수, 필드
calcArea(): 메소드

2.객체(=인스턴스)

class A{ int a; public getA(){ } } A a = new A();
A: 클래스
a: 객체 변수(참조값 저장)
new: 메모리(Heap)할당, 인스턴스 생성
A(): 생성자 호출
a가 생성되면 메모리 상에 a라는 이름의 방이 생성된다. 방에는 클래스A의 a와 getA()가 있는 heap의 주소가 들어 있다.
예제)원의 면적 구하기
class Circle { int radius; String color; double calcArea() { return 3.14 * radius * radius; } } public class CrircleTest { public static void main(String[] args) { Circle obj; //❶ obj = new Circle(); //❷ obj.radius = 100; obj.color = "blue"; //❸ double area = obj.calcArea(); //❹ System.out.println("원의 면적=" + area); } }
Plain Text
복사
obj의 데이터타입: 참조형, 메모리: 4byte
① 참조 변수 선언: 참조 변수는 주소값을 참조하기 때문에 참조변수라고 한다.
② 객체 생성(생성자): 객체를 생성하면 메모리에 obj라는 4byte방이 생성되고 방에는 주소(heap에 있는 redius, color, calcArea()의 번지수) 값이 들어간다.
*객체의 데이터 타입이 4byte 인 이유는 JVM이 기본적으로 32bit를 잡기 때문이다.
③ 객체의 필드 접근
④ 객체 메소드 접근

3.메소드(함수)

입력을 받아서 처리를 하고 결과를 반환한다.
메소드 오버로딩: 같은 함수 이름으로 파라미터 타입과 개수를 다르게 하는것이다.
메인 메소드부터 실행하게 된다.
void: 값을 반환하지 않음을 의미한다.
return: 값을 반환하는 것을 의미한다.
예제1)나이 출력하기
public static void main(String[] args) { System.out.println("프로그램의 시작"); hiEveryone(12); hiEveryone(13); System.out.println("프로그램의 끝"); } public static void hiEveryone(int age) { System.out.println("좋은 아침입니다."); System.out.println("제 나이는 " + age + "세 입니다."); }
Plain Text
복사
예제2)원의 넓이를 구하는 circleArea함수를 만들고 출력하기
public class ex2 { public static void main(String[] args) { double area = circleArea(10); System.out.println(area); } public static double circleArea(double radius) { return radius * radius * Math.PI; } }
Plain Text
복사
예제3)이름,학번,나이를 가지는 학생클래스를 생성하기
class Student { String name; String rollno; int age; public void printStudent() { System.out.println("학생의 이름:"+this.name); System.out.println("학생의 학번:"+this.rollno); System.out.println("학생의 나이:"+this.age); } } public class StudentTest { public static void main(String[] args) { Student student = new Student(); student.name = "Kim"; student.rollno = "20180001"; student.age = 20; student.printStudent(); } }
Plain Text
복사
예제4) 사각형의 넓이구하기
class Rectangle { double setWidth; double setHeight; public void setWidth(double width) { this.setWidth = width; //this: 자기 클래스내에있는 변수라는 것을 알려주기 위해 사용 } public void setHeight(double Height) { this.setHeight = Height; } public double getArea() { return setWidth * setHeight; } } public class RectangleTest { public static void main(String[] args) >{ Rectangle rec = new Rectangle(); rec.setWidth(10); rec.setHeight(10); System.out.println(rec.getArea()); } }
Plain Text
복사