JAJA 객체지향 총정리
*class 란?
쉽게말해서 붕어빵 틀이다.
붕어빵이 어떤 속성을 갖는지 어떤 모양을 갖는지는 붕어빵 틀처럼 정해져 있다.
*객체(instance)란?
밀가루, 팥, 슈크림등(<-매개변수) 원하는 매개변수(parameter)를 넣으면 만들어지는 붕어빵이다.
*class 이름 정의법
첫번째 문자는 대문자로 한다.
*instance 의 member에 접근하는 방법
선언한 객체 이름 '.' 접근하고싶은 member의 이름
ex)
class Phone{
String model;
}
public class Main{public static void main(String[]args){
Phone galaxy = new Phone();
galaxy.model = "Galaxy10";
System.out.println("모델은: " + galaxy.model);
}
}
*method란?
어떤 작업을 수행하는 코드를 하나로 묶어놓은 것이라고 생각하면 쉽다.
*method 예시
class Calculation{
int sum(int x, int y){
int result = x+y;
return result;
}
}
public class Main {
public static void main(String[] args) {
Calculation calculation = new Calculation();
int sumResult = calculation.sum(1,2);
System.out.println(sumResult);
}
}
*method 이름 정의
동사로 시작하고, 나머지 단어가 이어지면 대문자로 이어지게 작성한다.(camel case)
*생성자 constructor란?
instance(객체)가 생성될때 불리는 초기화 메소드
*생성자 이름정의
class이름과 동일하게 지어준다.
*생성자 예시
class Phone{
String model;
//constructor자동 생성단축키: (window)art+ insert, (mac)Command+N
Phone (String model){
this.model = model;
}
}
public class Main{public static void main(String[]args){
Phone galaxy = new Phone("Galaxy10");
System.out.println("모델은: " + galaxy.model);
}
}
*상속(inheritance)이란?
부모 class가 가진 속성을 자식 cass가 똑같이 물려 받는것.
자식 class는 부모가 가진 속성을 가지면서 다른 속성을 추가로 가질 수 있다.
*상속하는법
자식 클래스 뒤에 extends 부모 클래스
*상속 예시
//Animal 클래스 선언
class Animal{
String name;
public void cry(){
System.out.println(name + " is crying.");
}
}
//Animal클래스를 부모로 두는 자식클래스 Dog선언
class Dog extends Animal{
Dog(String name){
this.name = name;
}
//자식클래스에만 있는 메소드
public void swim(){
System.out.println(name + " is swimming.");
}
}
public class Main {
public static void main(String[] args) {
//Dog클래스타입의 Dog instance dog 선언
Dog dog = new Dog("코코");
dog.cry();
dog.swim();
//Animal클래스 타입의 Dog instance dog2 선언
//dog로 생성한 객체여도 Animal클래스타입 dog2는 swim메소드가 없음.
Animal dog2 = new Dog("미미");
dog2.cry();
//dog2.swim();
}
}
*overloading이란?
한 클래스 내에서 동일한 이름의 method를 여러개 갖는것.
*overloading의 조건
1. method이름이 동일해야함
2. 매개변수의 개수나 타입이 달라야함.
*overloading 예시
public class Main {
public static void main(String[] args) {
}
int add(int x, int y, int z){
return x+y+z;
}
//overloading parameter의 타입, 또는 개수가 다름.
long add(int a, int b, long c){
return a+b+c;
}
}
*overridding이란?
부모의 클래스에서 정의한 메소드를 자식클래스에서 한번더 정의하여,
덮어씌우는것.
*overriding 예시
class Animal {
String name;
String color;
public Animal(String name) {
this.name = name;
}
public void cry(){
System.out.println(name + " is crying");
}
}
class Dog extends Animal{
public Dog(String name) {
super(name);
}
//부모에 있는 메소드명과 같은 메소드명을 사용해서 overridding
@Override //어노테이션 붙여주기.
public void cry(){
System.out.println(name + " is barking");
}
}
public class Main {
public static void main(String[] args) {
//Animal 클래스타입의 Dog instance: dog 선언
Animal dog = new Dog("코코");
//instance가 Dog instance이기 때문에 cry메소드는 is barking으로 나온다.
dog.cry();
}
}
*접근제어자(access modifier)란?
class, member, parameter, method에 사용되며 외부에서의 접근을 제어하는 역할을 하는것.
*접근제어자의 종류:
private: 같은 클래스 내에서만 접근 가능
default: 같은 패키지 내에서만 접근 가능
protected: 같은 패키지 내에서, 그리고 다른 패키지의 자손 클래스에서 접근 가능
public: 접근에 제한이 없음
(좁음) -> (넓음)
private - default - protected - publick
*접근제어자 예시
----------------------------------package-------------------------------------------
package pkg;
public class ModifierTest {
private void messageInside(){
System.out.println("This is private modifier");
}
public void messageOutside(){
System.out.println("This is publick modifier");
messageInside();
}
protected void messageProtected(){
System.out.println("This is protected modifier");
}
//접근제어자를 선언하지 않았을때는 자동으로 packagePrivate로 접근제어자가 설정된다.
void messagePackagePrivate(){
System.out.println("This is package private modifier");
}
}
----------------------------------main-------------------------------------------
//같은패키지가 아닌 다른패키지에있는 class를 참조할때는 import가 추가된다.
//자바는 class를 package이름까지 포함해서 실제 class이름을 인식한다.
import pkg.ModifierTest;
class Child extends ModifierTest{
void callParentProtected(){
System.out.println("call my parent's protected method");
//super: 내가 상속받은 부모클래스를 가리키는 키워드.(여기서는 ModifierTest)
super.messageProtected();
}
}
public class Main {
public static void main(String[] args) {
//pkg 패키지 안에있는 ModifierTest타입으로 ModifierTest instance: modifierTest생성
ModifierTest modifierTest = new ModifierTest();
//modifierTest instance 에 있는 messageOutside method를 불러옴
modifierTest.messageOutside();
//messageInside method 는 private 접근제어자라서 같은 클래스 내에서만 접근이 가능하다.
//modifierTest.messageInside();
//messageProtected method 는 protected 접근제어자라서 같은 클래스 내에서, 다른페키지의 자손클래스에서만 접근이 가능하다.
//modifierTest.messageProtected();
//messageProtected method 가 자식 class 에 상속되었기때문에 불러오는것이 가능하다.
Child child = new Child();
child.callParentProtected();
//packagePrivate접근제어자는 메인함수에서 불러올 수 없다.
//modifierTest.messagePackagePrivate();
}
}
*추상클래스란?
추상메소드를 선언할 수 있는 클래스
*추상클래스의 특징
상속받는 자식클래스 없이 인스턴스 생성이 불가하다.
*추상 매소드란?
설계만 되어있고 구현체가 없는 매소드. ({}안에있는 바디가 없는 매소드.)
*추상클래스 예시
//추상클래스 선언
abstract class Bird{
private int x,y,z;
void fly(int x, int y, int z){
printLocation();
System.out.println("이동합니다.");
this.x = x;
this.y = y;
if(flyable(z)){
this.z = z;
}else{
System.out.println("그 높이로는 날 수 없습니다.");
}
printLocation();
}
//추상 매소드 선언 {}바디를 가질 수 없음.
abstract boolean flyable(int z);
public void printLocation(){
System.out.println("현재위치:(" + x + "," + y + "," + "," + z + ")");
}
}
class Pigeon extends Bird{
//flyable 메소드에 overriding 한다.
@Override
boolean flyable(int z) {
return z < 10000;
}
}
class Peacock extends Bird{
//flyable 메소드에 overriding 한다. 공작은 날 수 없으니 return값을 false로.
@Override
boolean flyable(int z) {
return false;
}
}
public class Main {
public static void main(String[] args) {
//추상클래스는 자체적으로 instance를 생성할 수 없다.
//Bird bird = new Bird();
Bird pigeon = new Pigeon();
Bird peacock = new Peacock();
System.out.println("----비둘기----");
pigeon.fly(1,1,3);
System.out.println("----공작새----");
peacock.fly(1,1,3);
System.out.println("----비둘기----");
pigeon.fly(1,1,30000);
}
}
*interface란?
모든 메소드가 추상메소드인 클래스
*interface의 특성
인터페이스명 앞에 interface 키워드를 선언해야한다.
함수의 특성인 접근제어자 return tipe, method이름만 정의한다.
인터페이스의 멤버는 상수와 메소드만 있으며 필드는 없다.
다중상속을 지원한다.
interface를 구현하는 클래스는 인터페이스에 존제하는 상세 내용을 반드시 구현 해야한다.
*interface 예시
//interface선언
interface Flyable {
void fly(int x, int y, int z);
}
//interface를 상속받는 자식클래스 Pigeon 선언
class Pigeon implements Flyable{
//필드 만들기
private int x,y,z;
//interface의 메소드 overriding
@Override
public void fly(int x, int y, int z){
printLocation();
System.out.println("날아갑니다.");
this.x = x;
this.y = y;
this.z = z;
printLocation();
}
public void printLocation() {
System.out.println("현재 위치(" + x + "," + y + "," + z +")");
}
}
public class Main {
public static void main(String[] args) {
//Flyabe 클래스 타입으로 Pigeon객체 pigeon 생성
Flyable pigeon = new Pigeon();
pigeon.fly(1,2,3);
}
}
*추상클래스와 인터페이스의 차이점

'개발 공부' 카테고리의 다른 글
| 이해가 안 가서 글 적으면서 공부하려고 만드는 페이지 (0) | 2022.12.26 |
|---|---|
| WIR (0) | 2022.12.25 |
| None값의 정의 (0) | 2022.12.14 |
| 회원가입, 로그인 기능구현 (0) | 2022.12.12 |
| 파이썬 try except (0) | 2022.12.12 |