클래스(Class)란?
java의 기본단위
자료형의 일종
java에서 이미 수많은 클래스들을 미리 만들어 놨지만
개발자(우리)가 새로 정의 할수있음
대문자로 시작하는 것이 규칙
함수(메서드명),변수명 등은 대문자xxx
import
이미 만들어져 있는 클래스를 사용하기위해선 import를 해야한다
Random,Scanner,...등
이미 만들어진 클래스들이 엄청 많음
클래스들이 너무 많기 때문에
서랍에 저장을 예쁘게 정리해놨습니다
패키지(라이브러리)
데이터 저장
int,double,..등은
원시타입이라 바로 값 저장가능하다
하지만 int[](배열),Random(클래스,객체),...등은 바로 값 저장이 안되기 때문에
힙 메모리 영역에서 생성하여 사용할수있다
이때 사용하는 연산자는 new를 사용해야하만한다!!
개발자(우리)가 새로 정의 할 수 있음
맴버변수를 가질수있음
맴버변수 필드 속성 어트리뷰트(attribute) 프로퍼티(property)
맴버함수=>★메서드
원시타입들은 new xxx
배열, 클래스, 객체(우리가 만든 자료형)들은
"개발자 영역(heap 메모리 영역을 사용하기때문에 new 사용)
class Student{//"학생이라는 자료형 정의(선언)완료
//"학생"이라는 자료형흔
// 이름,나이,점수를 가지고있음
//맴버변수
String name;
int age;
int score;
void printInfo(){
System.out.println("func()에서 출력중입니다");
System.out.println(name);//scope 가 맞기 때문에 사용가능
System.out.println(age);
System.out.println(score);
}
}
student
개발자(우리)가 만든 변수
"객체"라고 부른다
Student student=new Student();
개발자가 만든 자료형 Student 클래스 타입의
변수 student 객체를 new 연산자를 사용해서 heap 메모리 영역에 생성하겠습니다
가장 중요한 것
객체 지향언어를 사용하면
"누가 함수(메서드)를 호출했느냐"에 따라 결과가 달라집니다
객체지향언어를 한마디로 정의하라면
함수(메서드)에게 주어(주체)가 생기는 언어다
일반적인 함수는 주어(주체)가 없고
메서드(멤버함수)는 주어(주체)가 있다
★함수 != 메서드★
같은 메서드인데 다른 결과가 나오는 현상
==다형성
==다형성이 실현(구현)되었다
new연산자를 사용하면
==개발자 메모리 영역(heap메모리 영역)에 변수를 생성하면 자동 초기화 해준다!
원시타입인 변수들은 초기화하지 않으면 값이 없음-> 에러 발생
"아.. 멤버변수 초기화를 강제해줬으면 좋겠다.."
강제
ㅇㅇ기능 덕분에 ㅇㅇ을 강제 할수있다
좋은거임 많이쓰는거임
자유도가 높으면 사람이 많아질수록 결과물이 제각각이다
프로그래밍 언어에는 하면 안되거나 반드시 해야하는 것들을
"강제"하는기능들이 많이있음
Sutdent() 함수에 대하여
클래스와 이름이 똑같은함수
new 연산자 뒤에서 호출됨
역할 : 맴버변수 초기화하는 역할
"생성자"
생성자 없이는 객체를 생성할수없기때문에
JAVA에서 인자가 없는 생성자를 기본제공해 줍니다
기본제공되는 생성자를 "기본 생성자(디폴트 생성자)"
class Student{
String name;
int score;
//엥? 생성자 없는데요?
//자바가 기본 생성자(디폴트 생성자)를 기본 제공해줌
Student(){
System.out.println("클래스 기본 생성자 입니다");
//짜잔
//java가 기본제공해주던 애를 제가 직접 여러분들께 보여줬어용
name="이름없음";//멤버변수 초기화를 강제
score=0;
}
void printInfo() {
System.out.println(name+"학생은 "+score+"점입니다");
}
}
클래스에서 객체를 생성하는데
아..멤버변수 초기화을 강제하고 싶다
멤버변수 초기화하는 역할== 생성자
생성자란?
최초에 클래스를 정의하면 java가
인자없는 생성자 (기본생성자)를 제공해줌
클래스와 이름이 같으며
output을 명시 하지않는 특징이있습니다
아니 JAVA가 기본생성자를 준다면서??
생성자를 사용자(개발자)가 1개이상 정의하면
JAVA가 더이상 기본제공을 안합니다
class Student{
String name;
int score;
Student(String n) {
name=n;
score=0;
System.out.println("하나 더 만든 생성자");
}
Student(String n, int s) {//생성자 오버로딩
name=n;
score=s;
System.out.println("생성자로 멤버변수 초기화 강제");
}
void printInfo() {
System.out.println(name+"학생은 "+score+"점입니다");
}
}
메서드 VS 함수
함수에게 주어가 있는경우 주어가없음 funcA();main static(객체와 무관하게)
student.hello();
data.printInfo();
rand.nextInt();
sc.nextInt();
System.out.printIn();
.멤버접근 연산자
클래스명 객체명=new 생성자();
객체
클래스 타입의 변수
인스턴스 instance( !=object )
객체를 생성할때에는 new 생성자();
생성자
함수
클래스와 이름이 같음
멤버변수를 초기화하는 역할
어떤 클래스의 모든 객체가 다 동일한 멤버변수 값을 가질때에
우리는 그 멤버변수를 공유자원이라고 하며
객체와 무관하므로 static을 붙임
static이 붙은것 더이상 멤버변수가 아니다
그러므로 멤버변수를 초기화하는 생성자에서 초기화x
클래스에서 초기화
공유자원 -> 클래스 소속
멤버변수 → 객체(인스턴스) 소속
각각의 객체마다 다른값인가?
yes->멤버변수(속성)
각각의 객체가 다같은 값인가?
yes->static
클래스 소속
문제 1
ColorPoint 색깔점 클래스가 있습니다.
new ColorPoint(); // 검정(0,0)
new ColorPoint(1,2); // 검정(1,2)
new ColorPoint("분홍"); // 분홍(0,0)
new ColorPoint("빨강",3,5); // 빨강(3,5)
색깔점객체명.printInfo();
검정색 점은 (0,0)에 있습니다.
문제2
Circle 원 클래스가 있습니다.
new Circle(10); // 원 : 반지름 10 넓이 314.0
new Circle("도넛"); // 도넛 : 반지름 1 넓이 3.14
new Circle("피자",12); // 피자 : 반지름 12 넓이 452.16
HINT 모든 원들은 원주율(PI)이라는 3.14 값을 갖고있어용
원객체명.printInfo();
원는(은) 넓이가 314.0입니다.
피자는(은) 넓이가 452.16입니다.
package class04;
class ColorPoint{
String color;
int x;
int y;
ColorPoint(){
this(0,0);//하드코딩 최소화 하기!!
}
ColorPoint(int x,int y){
this("검정",x,y);
}
ColorPoint(String color) {
this(color,0,0);
}
ColorPoint(String color,int x,int y) {
this.color=color;
this.x=x;
this.y=y;
}
void printInfo() {
System.out.println(this.color+"색 점은 ("+this.x+","+this.y+")에 있습니다.");
}
void changeColor(String color) {
// TODO Auto-generated method stub
this.color=color;
}
public void move(int x, int y) {
// TODO Auto-generated method stub
this.x=x;
this.y=y;
}
}
class Circle{
static final double PI=3.14;//불변하는 변수== 상수(final)
//static
//모---- 든 원이라면 전부다 3.14 값을 가짐
//공유자원
//객체와 무관하게
String name;
int radius;
double area;
Circle(int radius){
this("원",radius);
}
Circle(String name){
this(name,1);
}
Circle(String name,int radius) {
this.name=name;
this.radius=radius;
this.area=radius*radius*Circle.PI;//공유자원은 클래스 소속이기때문에 클래스를 앞에 붙인다
}
void printInfo() {
//double area=this.radius*this.radius*this.PI;
System.out.println(name+"는(은) 넓이가 "+this.area+" 입니다.");
}
void changeRadius(int redius) {
// TODO Auto-generated method stub
this.radius=redius;
this.area=this.radius*this.radius*Circle.PI;
}
}
public class Test03 {
public static void main(String[] args) {
ColorPoint cp1= new ColorPoint(); // 검정(0,0)
ColorPoint cp2= new ColorPoint(1,2); // 검정(1,2)
ColorPoint cp3= new ColorPoint("분홍"); // 분홍(0,0)
ColorPoint cp4= new ColorPoint("빨강",3,5); // 빨강(3,5)
cp3.changeColor("빨강");
cp3.move(1,2);
cp1.printInfo();
cp2.printInfo();
cp3.printInfo();
cp4.printInfo();
Circle c1=new Circle(10); // 원 : 반지름 10 넓이 314.0
Circle c2=new Circle("도넛"); // 도넛 : 반지름 1 넓이 3.14
Circle c3=new Circle("피자",12); // 피자 : 반지름 12 넓이 452.16
c2.changeRadius(10);
c1.printInfo();
c2.printInfo();
c3.printInfo();
}
}