자바 무료강의 2시간 완성을 시청하고 간략히 정리
데이터와 기능을 포함하는 코드 묶음
설계도, 설명서 역할을 한다.
클래스로 만들어진 실체를 "객체"라 부른다.
예를 들어, 종이학을 접는 설명서를 클래스,
설명서를 보고 접은 종이학은 객체라고 생각하면 된다.
class 클래스명{
}
public class Main {
public static void main(String[] args) {
Person person = new Person();// 클래스 사용
}
}
// 클래스 선언
class Person{
}
클래스 내에 선언된 변수
객체마다 다른 값을 가질 수 있다.
class 클래스명{
인스턴스 변수1
인스턴스 변수2
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
person.age = 19; // . 으로 인스턴스 변수에 접근
person.name = "자두";
// 각 객체별 다른 값을 가질 수 있다.
Person person2 = new Person();
person2.age = 30; // . 으로 인스턴스 변수에 접근
person2.name = "포도";
}
}
// 인스턴스 변수를 선언한 클래스
class Person{
int age;
String name;
}
클래스 내에 static으로 선언된 변수(인스턴스 변수와의 차이)
모든 객체가 공유하는 변수
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.age = 19;
person.name = "자두";
// 각 객체별 다른 값을 가질 수 있다.
Person person2 = new Person();
person2.age = 30; // . 으로 인스턴스 변수에 접근
person2.name = "포도";
Person.personCount = 10;// 객체를 만들 필요 없이, 클래스 명으로 접근 가능
System.out.println(Person.personCount); // 10
System.out.println(person.personCount); // 10
System.out.println(person2.personCount); // 10
}
}
class Person{
int age;
String name;
static int personCount = 0;
}
클래스 내에 정의된 메소드
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.age = 19;
person.name = "자두";
// 각 객체별 다른 값을 가질 수 있다.
Person person2 = new Person();
person2.age = 30; // . 으로 인스턴스 변수에 접근
person2.name = "포도";
Person.personCount = 10;
person.introduce(); // "I'm 자두, and 19 years old"
person2.introduce();// "I'm 포도, and 30 years old"
}
}
class Person{
int age;
String name;
static int personCount = 0;
// 인스턴스 메소드
public void introduce(){
System.out.println("I'm "+name+", and "+age+" years old");
}
}
클래스 내에 static으로 정의된 메소드
class 클래스명{
static 클래스 메소드1
static 클래스 메소드2
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.age = 19;
person.name = "자두";
Person person2 = new Person();
person2.age = 30; // . 으로 인스턴스 변수에 접근
person2.name = "포도";
Person.personCount = 10;
Person.printPersonCount(); // 클래스 메소드 사용
}
}
class Person{
//인스턴스 변수
int age;
String name;
//인스턴스 메소드
public void introduce(){
System.out.println("I'm "+name+", and "+age+" years old");
}
// 클래스 변수
static int personCount = 0;
// 클래스 메소드
public static void printPersonCount(){
System.out.println("personCount = "+personCount);
}
}
자기 자신(인스턴스, 지역 변수 구분 위해 사용)
this.인스턴스 변수
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.age = 19;
person.setNames("자두");
}
}
class Person{
//인스턴스 변수
int age;
String name;
public void setNames(String name){// 파라메터와 인스턴스 변수의 이름이 같음
this.name = name;// 구분위해 this 사용
}
}
객체가 생성될 때 호출되는 메소드
클래스명(전달값){
초기화 명령문;
}
public class Main {
public static void main(String[] args) {
Person person = new Person("자두", 19);
}
}
class Person{
//인스턴스 변수
int age;
String name;
Person(String name, int age){
this.name = name;
this.age = age;
}
}
getter : 인스턴스 변수의 값 반환
settet : 인스턴스 변수 값 설정
getter
반환형 get이름(){
return 반환값;
}
setter
void set이름(전달값){
}
class Person{
//인스턴스 변수
int age;
String name;
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
접근 권한 지정
접근제어자 class 클래스명{
접근제어자 인스턴스 변수
접근제어자 인스턴스 메소드
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.age = 19; // error!
person.setAge(19); // 이렇게 접근하여 값 설정 가능
}
}
class Person{
//인스턴스 변수
private int age;
String name;
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
접근 제어자 | 접근 가능범위 |
---|---|
private | 해당 클래스 내에서만 |
public | 모든 클래스에서 |
default | 같은 패키지 내에서만(아무것도 적지 않았을때 == 생략했을때) |
protected | 같은 패키지 내에서, 다른 패키지인 경우 자식 클래스에서 |
관련 클래스들을 그룹화(폴더 개념)
package 패키지명;
package 패키지명.클래스명;
package 패키지명.*; // 패키지 안의 여러 클래스를 한번에 접근할 수 있다.
Person 객체를 별도의 패키지 안에 정의해보자.
src 에서 우클릭 하여 패키지를 만든다.(이름은 sample)
Person 클래스를 sample 패키지로 옮기고, Main.java에서
import sample.Person; 하여 sample 패키지 안의 Person 객체를 사용하였다.
특정 클래스의 기능을 재사용 및 확장
부모 클래스 : 자식 클래스의 기본 기능을 정의함
자식 클래스 : 부모 클래스에서 정의한 기본 기능을 사용할 수 있고, 자체적으로 새로운 기능을 정의하여 사용할 수 있다.
==> 부모 클래스의 기능을 재사용 + 새로운 기능을 구현할 수 있다.
자식 클래스명 extends 부모 클래스명{
}
부모 클래스의 메소드를 재정의
덮어 쓰기
자식 클래스에서 재정의한 메소드가 우선순위가 더 높음
여러 형태로 동작할 수 있는 성질
부모클래스 변수명 = new 자식클래스();
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.setName("자두");
student.setAge(19);
student.schoolName = "만두";
student.introduce();
Person student2 = new Person();
student2.setName("바나나");
student2.setAge(12);
student2.introduce();
Person student3 = new Student();//다형성
student3.setName("사과");
student3.setAge(13);
//student3.schoolName = "만두"; // Error!
student3.introduce();
}
}
결과
저는 자두이고요, 19 살이에요. 만두 학교에 다녀요.
저는 바나나이고요, 12 살이에요.
저는 사과이고요, 13 살이에요. null 학교에 다녀요.
부모 클래스에 접근하기 위해 사용
super.부모클래스변수;
super.부모클래스메소드();
super();
객체의 메모리 주소를 가리킴
자료형 | 설명 | 종류 |
---|---|---|
기본 자료형 | 실제 값 저장 | int, float, double, long, boolean |
참조 자료형 | 값이 저장된 메모리 주소를 저장 | String, Person, Student, .. |
int a = 10;
int b = 20;
a = b;
a | b |
---|---|
10 | 20 |
a=b; 이후
a | b |
---|---|
20 | 20 |
String a = "사과";
String b = "바나나";
a = b;
a | b |
---|---|
사과 | 바나나 |
a=b; 이후
a,b | |
---|---|
사과 | 바나나 |
"바나나"데이터가 있는 메모리를 a,b 둘 다 참조하게됨
변경할 수 없게 만드는 키워드
age에 final 을 사용하면 age 값을 변경할 수 없다는 error 발생
상수들의 묶음
enum 열거형명{
상수명1,
상수명2,
...
}
enum Gender{
MALE,
FEMALE,
}
// Gender.java
package sample;
public enum Gender{ // 외부에서 접근해 쓰려면 public 선언
MALE,
FEMALE,
}
// Person.java
package sample;
public class Person {
private int age = 10;
private String name;
private Gender gender; // enum 으로 형 선언
public Person(int age, String name, Gender gender){
this.age = age;
this.name = name;
this.gender = gender;
}
public void introduce(){
System.out.println("저는 "+name+"이고요, "+age+" 살이에요.");
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
// Student.java
package sample;
public class Student extends Person{
public String schoolName;
public Student(int age, String name, Gender gender, String schoolName){
super(age, name, gender);
this.schoolName = schoolName;
}
public void introduce(){
System.out.println("저는 "+getName()+"이고요, "+getAge()+" 살이에요. "+schoolName+" 학교에 다녀요.");
}
}
// Main.java
import sample.Gender;
import sample.Person;
import sample.Student;
public class Main {
public static void main(String[] args) {
Student student = new Student(19, "자두", Gender.FEMALE, "만두");
student.introduce();
Person student2 = new Person(21, "포도", Gender.FEMALE);
student2.introduce();
Person student3 = new Student(18, "사과", Gender.FEMALE, "만두");
student3.introduce();
}
}
// 결과
저는 자두이고요, 19 살이에요. 만두 학교에 다녀요.
저는 포도이고요, 21 살이에요.
저는 사과이고요, 18 살이에요. 만두 학교에 다녀요.
아직 완성되지 않은 클래스
abstract class 클래스명{
}
// 선언만
abstract class Shape{
abstract double calculateArea();
}
// Shape 을 구현
class Square extends Shape{
private double s;
public Square(double s){
this.s = s;
}
@Override
double calculateArea() {
return s * s;
}
}
// Shape 을 구현
class Circle extends Shape{
private double r;
public Circle(double r){
this.r = r;
}
@Override
double calculateArea() {
return Math.PI * r * r;
}
}
클래스를 작성할 때 기본이 되는 뼈대
interface 인터페이스명{
}
interface Shape{
double calculateArea();
}
class Square implements Shape {
private double s;
public Square(double s){
this.s = s;
}
@Override
public double calculateArea() {
return s * s;
}
}
class Circle implements Shape {
private double r;
public Circle(double r){
this.r = r;
}
@Override
public double calculateArea() {
return Math.PI * r * r;
}
}