Class : 붕어빵 틀과 같은 개념
instance : 틀에서 만들어진 붕어빵 같은 개념 -> Class로부터 만들어진 객체
class Phone {
String model;
String color;
int price;
}
public class Main {
public static void main(String[] args) {
Phone galaxy = new Phone();
galaxy.model = "Galaxy10";
galaxy.color = "Black";
galaxy.price = 100;
Phone iphone =new Phone();
iphone.model = "iPhoneX";
iphone.color = "Black";
iphone.price = 200;
System.out.println("철수는 이번에 " + galaxy.model + galaxy.color + " + 색상을 " + galaxy.price + "만원에 샀다.");
System.out.println("영희는 이번에 " + iphone.model + iphone.color + " + 색상을 " + iphone.price + "만원에 샀다.");
}
}
여기서 Phone이 class, galxy나 iphone이 instance가 됩니다.
instance의 멤버변수에 접근할 때는 이름 뒤에 .을 찍고 멤버 변수에 해당하는 값을 할당해주면 된다.
int add(int x, inty) {
int result = x +y;
return result;
}
add 앞의 int는 이 함수의 결과값이 저장되는 타입(return type)
int x, int y는 파라미터 여기 있는 in x와 y는 함수 안에서만 존재 한다. 여기서 반환타입이 void면 '아무것도 없음'을 의미한다. 메소드 내에서 출력을 할 경우 사용되는 듯 하다.
class Phone {
String model;
String color;
int price;
Phone (String model, String dolor, int price){
this.model = model;
}
}
public class Main {
public static void main(String[] args) {
Phone galaxy = new Phone();
Phone iphone =new Phone();
System.out.println("철수는 이번에 " + galaxy.model + galaxy.color + " + 색상을 " + galaxy.price + "만원에 샀다.");
System.out.println("영희는 이번에 " + iphone.model + iphone.color + " + 색상을 " + iphone.price + "만원에 샀다.");
}
}
this.뒤에 있는 model이 Phone 클래스에 있는 model과 같다. = 뒤의 model은 파라미터에 있는 model과 같다.
-> 객체에 있는 model이라는 변수에 파라미터에서 받은 model를 할당 할 거다.
Alt + Insert 누르면 자동으로 생성해주는 창이 열린다.
기존의 클래스를 재사용하는 방식 중의 하나로, 한번 작성한 코드를 변경 사항만 적용시켜서 상대적으로 적은 양의 코드를 작성할 수 있게 된다.
특징 : 부모 클래스에서 정의된 필드와 메소드를 물려 받는다. 새로운 필드와 메소드를 추가할 수 있다. 부모 클래스에서 물려받은 메소드를 수정할 수도 있다. 오직 하나의 클래스만 상속 받을 수 있다.
class Animal{
String name;
public void cry(){
System.out.println(name+"is crying");
}
}
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 = new Dog("코코");
dog.cry();
dog.swim();
Animal dog2 = new Dog("미미"); // animal type의 dog2라는 변수인데 실제는 dog로 생성한 객체
dog2.cry();
// dog2.swim(); // 실제 객체는 Dog지만 변수를 선언하는 type이 Animal로 되어있기 때문에 swim은 호출 불가
}
}
public class Main {
public static void main(String[] args) {
// write your code here
}
int add(int x, int y, int z){
return x+y+z;
}
int add(int a, int b){
return a+b;
}
}
부모 클래스의 메소드와 이름, 매개변수, 반환 타입이 같아야 한다
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);
}
@Override
public void cry(){
System.out.println(name+"is barking");
}
}
public class Main {
public static void main(String[] args) {
// write your code here
Animal dog = new Dog("코코");
dog.cry(); //코코is barking이 출력, cry()가 Override 되어 자식 클래스에 있는 함수를 호출했기 때문
}
}