https://kephilab.tistory.com/47?category=395674
class { method ( ) { ; } }
public class Main {
public static void main(String[] args){
}
}
변수의 종류 선언된 위치에 따라 - 인스턴스변수, 클래스변수(static 변수), 지역변수
클래스 이름과 메소드 이름이 같다.
반환되는 리턴 타입이 없다.
클래스 내에 생성자가 없을경우 기본생성자를 컴파일러가 제공한다.
클래스타입 객체변수(참조변수) = new 클래스(매개변수,파라미터//생략가능)
new = 인스턴스 생성 및 객체에 참조값 리턴
구체화, 구현화, 객체생성...
public, protected, (default), private
static, final, abstract, ...
매모리에 할당(new)하지 않아도 실행이 가능함.
컴파일되는 시점에 정의되어서, 객체화 하지 않아도 실행 가능하다.
static 요소를 static이 아닌 요소에서 호출하는 것은 불가능하다.
class MyMath2 {
long a,b;
long add() { return a + b; }
static long add(long a, long b) { return a + b; }
}
class Ex6_9 {
public static void main(String[] args){
MyMath2 mm = new MyMath2();
mm.a = 200L;
mm.b = 100L;
System.out.println(mm.add());
System.out.println(MyMath2.add(200L,100L));
}
}
static 변수는 인스턴스를 생성하지 않아도 '클래스명.클래스변수'로 사용이 가능하다.
static 변수는 하나의 저장공간을 공유함으로 수정하면 모든 인스턴스에 값이 변화한다.
데이터나 기능을 외부에서 직접 접근하지 않고 함수를 통해서만 접근
정보 은닉화를 통해 높은 응집도, 낮은 결합도를 유지할 수 있도록 설계하는 것
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Main {
public static void main (String[] args){
myObj.setName("John");
System.out.println(myObj.getName());
}
}
기존의 클래스를 재사용 하여 새로운 클래스를 작성
public class Ex7_4 {
public static void main(String[] args){
Point3D p =new Point3D(1, 2, 3);
System.out.println("x=" + p.x + ",y="+p.y + ",z=" + p.z);
}
}
class Point{
int x,y;
Point(int x, int y){
this.x = x;
this.y = y;
this는 생성자는 클래스 내의 멤버변수와 지역변수의 이름이 같을 경우 구분을 사용
super는 자식 클래스가 조상 클래스로부터 상속받은 멤버의 이름이 같을 경우 를 참조할 때 사용
// Point(int x1, int y1){
// x = x1;
// y = y1;
}
}
class Point3D extends Point {
int z;
Point3D(int x, int y, int z){
super(x,y); // Point(int x, int y); 호출
super()는 부모 클래스의 생성자를 호출하는 메서드입니다
this.z= z;
}
}
-한가지 타입의 참조 변수로 여러 타입의 객체를 참조 할수 있음
-조상클래스 타입의 참조 변수로 자손클래스의 인스턴스를 참조할수 있음.
-서로 다른 클래스의 객체,변수,매소드가 같은 동작 수행 명령을 받았을 때, 각자의 특성에 맞는 방식으로 상황에 따라 다른 결과를 내는 것
class Car2{
String color;
String gearType;
int door;
Car2() {
this("white", "auto", 4);
}
this()는 한 생성자에서 다른 생성자를 호출 할 떄사용한다.
// Car2(){
// color = white;
// gearType = auto;
// door = 4;
// }
Car2(String color){
this(color, "auto", 4);
}
Car2(String color, String geraType, int door){
this.color = color;
this.gearType = geraType;
this.door = door;
}
}
public class Main {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "white";
c1.gearType = "auto";
c1.door = 4;
Car c1 = new Car();
Car c2 = new Car("blue");
}
}
class Product {(생략)}
class Tv extends Product{(생략)}
class Computer extends Product{(생략)}
class Audio extends Product{(생략)}
class Buyer{void buy(Product p)}
public class Ex7_8 {
public static void main(String[] args){
Buyer b = new Buyer();
Tv1 t = new Tv1();
b.buy(t);
// b.buy(t.Tv1()); //안됨
// b.buy(Tv1()); //안됨
b.buy(new Tv());
b.buy(new Computer());
b.buy(new Audio());
//buy는 매개변수가 있어야한다(매개변수의 다형성)
//b.buy()를 배열로 만들기
//조상타입의 참조변수로 자손타입의 인스턴스를 참고하는것이 가능함
Tv t = new Tv();
Prouduct p = new Tv(); //둘다가능
Product2[] item = {new Tv2(), new Computer2(), new Audio2()};
for(int i=0; i < item.length; i++){
b.buy(item[i]);
}
//배열에 생성자를 넣기위해서
// 부모클래스로 배열 형식을 지정함
}
class Ex7_7 {
public static void main(String[] args) {
// Car car = new Car();
Car car =null;
FireEngine fe = new FireEngine();
FireEngine fe2 = null;
fe.water();
car = fe; // car = (Car)fe; 형병환 생략됨
car.drive(); // 가능
// car.wather(); //불가능
System.out.println(car instanceof FireEngine); //형병환 가능한지 확인
fe2 = (FireEngine)car; //형변환 생략 불가능
fe2.water();
}
}
class Car {
String color;
int door;
void drive() {
System.out.println("dirbe, Brrrrrr~");
}
void stop() {
System.out.println("stop!!");
}
}
class FireEngine extends Car {
void water() {
System.out.println("water!!");
}
}
오버라이딩은 상위 클래스의 메서드를 하위 클래스에서 재정의하는 것을 말한다.
//오버로딩 (로드= 적재)파라미터가 다름
//오버라이딩 write(메서드, 파리터가 같다)다시한번 적는다.
class Card2 {
String kind;
int number;
Card2() {
this("SPADE", 1);
}
Card2(String kind, int number){
this.kind = kind;
this.number = number;
}
public String toString(){
return "kind : " + kind + ",number : " + number;
}
}
public class Ex9_5 {
public static void main(String[] args){
Card2 c1 = new Card2();
Card2 c2 = new Card2("HEART",10);
System.out.println(c1.toString());
System.out.println(c2.toString());
}
}
int 10이 toString()을 통해 String으로 변환됨
인터페이스로 클래스들의 공통적인 특성(변수, 메소드)들을 묶어 표현하는 것.
abstract를 접근 제어자 뒤에 작성
접근 제어자 abstract class 클래스명 {
접근 제어자 abstract 반환형 메소드명();
}
일반메서드 및 맴버변수를 구성원으로 가질수 없음
class Product{
int price;
int bonusPoints;
Product(){} // 기본 생성자 추가
Product(int price){
this.price = price;
bonusPoints = (int)(price/10.0);
}
}
class Tv extends Product {
Tv(){} //조상클래스에 기본 생성자가 없어서 오류남
// Tv(){super();}
public String toString(){
return "Tv";
}
}
class Exercise7_3 {
public static void main(String[] args){
Tv t = new Tv();
}
}
class MyTv {
private boolean isPowerOn;
private int channel;
private int volume;
final int MAX_VOLUME = 100;
final int MIN_VOLUME = 0;
final int MAX_CHANNEL = 100;
final int MIN_CHANNEL = 1;
int prevChannel;
// public int getChannel(){}
// return channel;
// public void setChannel(int channnel){
// setChannel = channnel;
// }
// 코드 작성 최대,최소 채널, 볼륨일때 메세지 보내기
public int getChannel() {
return channel;
}
public void setChannel(int channel) {
if (channel < MIN_CHANNEL) {
channel = MAX_CHANNEL;
System.out.println("max 체널로 변경합니다.");
} else if (channel > MAX_CHANNEL) {
channel = MIN_CHANNEL;
System.out.println("min 체널로 변경합니다.");
}
prevChannel = this.channel;
this.channel = channel;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
if (volume > MAX_VOLUME || volume < MIN_VOLUME) {
return;
}
this.volume = volume;
}
//코드작성 이전체널로이동
void gotoPrevChannel() {
setChannel(prevChannel);
}
}
public class Exercise7_4 {
public static void main(String[] args){
MyTv t = new MyTv();
t.setVolume(10);
System.out.println("VOL:" + t.getVolume());
t.setChannel(10);
System.out.println("CH:" + t.getChannel());
t.setChannel(20);
System.out.println("CH:" + t.getChannel());
t.gotoPrevChannel();
System.out.println("CH:" + t.getChannel());
t.gotoPrevChannel();
System .out.println("CH:" + t.getChannel());
}
}
//abstract class Amimal {}
interface Animal {
public void animalSound();
public void sleep();
// void walk();
/*인터페이스에 정의된
모든 추상 메서드를 구현화 해야한다.
일부만 구현화 할경우 abstract를 붙여 추상 클래스로 선언해야한다.*/
}
class Pig implements Animal{
public void animalSound(){
System.out.println("pig Say : wawawawa");
}
public void sleep(){
System.out.println("Zzzzzz");
}
}
class Main{
public static void main(String[] args){
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}