import java.util.Calendar; //오늘날짜를 출력하기 위해서
public class Date {
private int year, month, day;
public Date(){ //Default Constructor
Calendar now = Calendar.getInstance();
this.year = now.get(Calendar.YEAR);
this.month = now.get(Calendar.MONTH) +1;
this.day = now.get(Calendar.DATE);
}//기본생성자를 쓰는 것만으로도 오늘의 날짜를 알게.
@Override
public String toString(){ //그냥 출력을 하게되면 Date@1975d24 이런식으로 toStrig을 호출한다. 그래서 toString을 오버라이딩하는 작업.
return "Today is " + this.year + "년 " + this.month + "월 " + this.day + " 일...";
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}
public class EncapDemo {
public static void main(String[] args) {
Date today = new Date();
//Date worldcup = new Date(2014,6,15); //아직 생성자를 이렇게 만들어주지않아 사용불가
System.out.println(today); //today.toString을 호출한다.
}
}
출력:
Today is 2014년 3월 18 일...
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
/*
* 1. this. --> 나의 -->나의 멤버변수, 나의 멤버메소드를 명시적으로 지칭할 때 사용
* 2. this --> 나 --> 나전체를 파라미터나 리턴할 때 사용
* 3. this() --> 나의 생성자가 나의 또 다른 생성자를 호출할 때 사용
* 1) 반드시 생성자 메소드에서만 사용한다.
* 2) 반드시 생성자 메소드 속에서 첫번째 줄에 사용해야 한다.
*/
public class ThisDemo {
public static void main(String[] args) {
Demo d = new Demo(); System.out.println(d);
Demo d1 = new Demo("Sally"); System.out.println(d1);
Demo d2 = new Demo(25); System.out.println(d2);
Demo d3 = new Demo("Michael", 40); System.out.println(d3);
}
}
class Demo{
private String name;
private int age;
public Demo(){
//new Demo("unknown" , 20); //new를 위에서 쓰고 또 new 를 쓰면 주소가 바뀐다.
this("unknown", 20);
}
public Demo(String name){
//new Demo(name, 20);
this(name, 20);
}
public Demo(int age){
//new Demo("unknown", age);
this("unknown", age);
}
public Demo(String name, int age){
this.name = name;
this.age = age;
}
@Override
public String toString(){
return "name = " + name + ", age = " + age;
}
}
출력:
name = unknown, age = 20
name = Sally, age = 20
name = unknown, age = 25
name = Michael, age = 40
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
Instance Initialization Block
public class Car {
private String maker;
private String name;
private int price;
private final double PI;
{//초기화블록은 변경이 불가하고, 처음 한번만 호출되고, 다음부터는 호출이 불가능하다.
System.out.println("나는 초기화 블록");
this.maker = "Kia";
this.name = "K5";
this.price = 20_000_000;
this.PI = 3.14; //처음에 값을 정하고 바뀌지 않는 것이면 초기화블록에 넣어줘도 괜찮다.
}//생성자보다 먼저 메모리에 올라온다.
public Car(String maker, String name, int price) {
System.out.println("나는 생성자 메소드");
this.maker = maker;
this.name = name;
this.price = price;
}
@Override
public String toString(){
return "maker = " + this.maker + ", name = " + this.name + ", price = " + this.price;
}
}
public class ConstructorDemo {
public static void main(String[] args) {
Car car = new Car("현대", "Sonata", 20000000);
//Car car = new Car();
System.out.println(car);
}
}
출력:
나는 초기화 블록
나는 생성자 메소드
maker = 현대, name = Sonata, price = 20000000
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
상속(Inheritance) :starUML에서 Generallization : 직선화살표에 속이 빈 삼각형 모양
class TwoD{
int x,y;
public void display(){
System.out.printf("(x,y) = (%d, %d)\n", x, y);
}
}
class ThreeD extends TwoD{
int z;
public void print(){
System.out.printf("(x,y,z) = (%d, %d, %d)\n", x,y,z);
}
}
public class SangsokDemo {
public static void main(String[] args) {
ThreeD td = new ThreeD();
td.print();
}
}
출력:
(x,y,z) = (0, 0, 0)
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
private은 상속되지않는다
생성자는 상속되지않는다.
static은 상속과 관련이없다.
overshhadow, override 메소드는 상속되지않는다.
public class Point { //모든객체는 오브젝트의 자식. extends Object가 생략되어 있음.
private int x, y;
public Point(){//만약 부모클래스의 기본생성자가 없으면 자식클래스에서 오류발생. 부모가 기본생성자를 만들어주던지, super를 써서 처리해주던지..
System.out.println("부모의 기본생성자");
}
public Point(int x){
this.x = x;
System.out.println("나는 부모 생성자");
}
public void display(int num){
System.out.println("나는 부모의 메소드");
}
}
public class SubPoint extends Point{
private int num;
public static void main(String[] args) {
SubPoint sp = new SubPoint();
//System.out.println(sp.x);
}
public SubPoint(){ //자식은 항상 부모의 기본생성자만 호출한다.
//super(5);
this.num = num;
System.out.println("나는 자식생성자");
}
public SubPoint(int num, int x){
//this(num);
super(x); //this나 super는 가장 먼저 써줘야한다. this를 주석처리하고 아래와 같이 써줌으로써 오류를 피한다.
this.num = num;
}
}
출력:
부모의 기본생성자
나는 자식생성자
-----------------------------------------------
public class Box {
private int width;
private int height;
private int depth;
public Box(int width, int height, int depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
public void display(){
System.out.printf("width = %d, height = %d, depth = %d\n", width, height, depth);
}
}
public class BoxWeight extends Box{
private int weight;
public BoxWeight(int width, int height, int depth, int weight){
super(width, height, depth);
this.weight = weight;
}
public void displayWeight(){
System.out.printf("wieght = %d\n", weight);
}
}
public class ShippedBox extends BoxWeight {
private int shippingprice;
public ShippedBox(int width, int height, int depth, int weight, int shippingprice){
super(width, height, depth, weight);
this.shippingprice = shippingprice;
}
public void displayShipprice(){
System.out.printf("shippingprice = %d\n", shippingprice);
}
}
public class SangsokDemo1 {
public static void main(String[] args) {
ShippedBox sb = new ShippedBox(10,20,30,40,500);
sb.display(); //Box
sb.displayWeight(); //BoxWeight
sb.displayShipprice();
}
}
출력 :
width = 10, height = 20, depth = 30
wieght = 40
shippingprice = 500
----------------------------------------------------
public class Bumo {
static int num; //static variable
int su; //member variable
}
public class Jasik extends Bumo{
public void display(){
System.out.println("num = " + num + ",su = " + su);
}
}
public class SangsokDemo2 {
public static void main(String[] args) {
Jasik ja = new Jasik();
ja.display();
ja.su = 100; //Jasik주소로 접근.
Bumo.num = 1000; //static은 자식필요없이 부모에게 직접 접근을할 수 있다. 이것은 상속이아니다.
ja.display();
}
}
출력:
num = 0,su = 0
num = 1000,su = 100
---------------------------------------------------
public class SangsokDemo3 {
public static void main(String[] args) {
Lion king = new Lion();
System.out.println("age = " + king.age);
king.display();
}
}
class Mammal{
int age = 50; //자식과 이름이 같으면 상속되지 않는다.
public void display(){ System.out.println("나는 부모의 메소드"); } //override메소드는 상속되지 않는다.
}
class Lion extends Mammal{
String age = "25"; //overshadow variable - 부모와 변수의 이름이 같음.
public void display(){ System.out.println("나는 자식의 메소드"); } //메소드는 리턴타입 변수이름
}
출력:
age = 25
나는 자식의 메소드
----------------------- overshadow 해결
public class SangsokDemo3 {
public static void main(String[] args) {
Lion king = new Lion();
// System.out.println("age = " + king.age);
king.print();
}
}
class Mammal{
int age = 50; //자식과 이름이 같으면 상속되지 않는다.
public void display(){ System.out.println("나는 부모의 메소드"); } //override 메소드는 상속되지 않는다.
}
class Lion extends Mammal{
String age = "25"; //overshadow variable - 부모와 변수의 이름이 같음.
public void print(){
System.out.println("this.age = " + this.age);
System.out.println("super.age = " + super.age);
}
public void display(){ System.out.println("나는 자식의 메소드"); } //메소드는 리턴타입 변수이름
}
출력:
this.age = 25
super.age = 50
-------------------------override 해결
public class SangsokDemo3 {
public static void main(String[] args) {
Lion king = new Lion();
// System.out.println("age = " + king.age);
king.print();
}
}
class Mammal{
int age = 50; //자식과 이름이 같으면 상속되지 않는다.
public void display(){ System.out.println("나는 부모의 메소드"); } //override 메소드는 상속되지 않는다.
}
class Lion extends Mammal{
String age = "25"; //overshadow variable - 부모와 변수의 이름이 같음.
public void print(){
//System.out.println("this.age = " + this.age);
//System.out.println("super.age = " + super.age);
super.display();
this.display();
}
public void display(){ System.out.println("나는 자식의 메소드"); } //메소드는 리턴타입 변수이름
}
출력:
나는 부모의 메소드
나는 자식의 메소드
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
public class OverrideDemo extends Object{
private int age;
public OverrideDemo(int age){ this.age = age;}
public static void main(String[] args) {
OverrideDemo od = new OverrideDemo(25);
System.out.println(od);
System.out.println(od.toString());
}
@Override
public String toString(){ //
//return "age = " + age; 아래처럼 쓴 것과 값이 같다.
return String.format("age = %d", this.age);
}
}
출력:
age = 25
age = 25
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
/*
* 비교
* 1. Premitive type
* 1) == 연산자만 사용
* 2)값비교
* 2. Reference type
* 1) ==연산자, equals() 메소드
* 2) 주소비교만한다.
* 3. String type
* 1) 값비교 : equals()
* 2) 주소비교 : ==연산자
*/
public class EqualsDemo {
public static void main(String[] args) {
Test t = new Test(); t.num = 100;
Test t1 = new Test(); t1.num = 100;
if(t.num == t1.num) System.out.println("같다"); //if(t.equals(t1)) 절대주소 비교. t==t1과 같음.
else System.out.println("다르다");
}
}
class Test{
int num;
}
-----------------------string type 비교
public class EqualsDemo {
public static void main(String[] args) {
String str = "Hello";
String str1 = "Hello"; //두개의 값이 같으면 기존번지를 활용한다.
if(str == str1) System.out.println("같다"); //if(str.equals(str1)) 로 써도 출력은 같다.
else System.out.println("다르다");
}
}
class Test{
int num;
}
출력:
같다
-------------------
public class EqualsDemo {
public static void main(String[] args) {
String str = new String("Hello");
String str1 = new String("Hello");
if(str == str1) System.out.println("같다"); //if(str.equals(str1))로하면 출력은 같다로 나온다.
else System.out.println("다르다");
}
}
class Test{
int num;
}
출력:
다르다
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
//equals() 메소드의 재정의
public class OverrideDemo1 {
public static void main(String[] args) {
Point p = new Point(100, 200);
Point p1 = new Point(100,200); //각각의 x와 y가 같은 지 비교하기위해 equals를 재정의
if(p.equals(p1)) System.out.println("같다");
else System.out.println("다르다");
}
}
public class Point { //모든객체는 오브젝트의 자식. extends Object가 생략되어 있음.
private int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
@Override
public String toString(){
return String.format("(x,y) = (%d,%d)" , this.x, this.y);
}
@Override
public boolean equals(Object obj){
Point copy = (Point)obj;
if(this.x == copy.x && this.y == copy.y)return true;
else return false;
}
}
출력:
같다
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
다형성(Polymorphism)
/*
* Casting (Conversion)
* 1. Primitive type
* 1) cast() 연산자
* 2) implicit conversion, 암묵적, 자동형변환 : 작은 사이즈 --> 큰 사이즈
* 4 + 89.5 --> 4.0 + 89.5 --.> double
* 123 + "Hello" --> "123Hello"
* 3) explicit conversion, 명시적, 강제적 형변환, demotion : 큰사이즈 --> 작은사이즈
* 89.5 --> (int)89.5
* 2. Reference type
* 1) 부모 자식 간 관계일 때
* 2) 자식 --> 부모 : 강제적, 자동적 모두 가능
* 3) 부모 --> 자식 : 강제적 형변환만 가능하고, 런타임때 instanceof 연산자로 체크해야한다(컴파일은되고 런타임때는 안될 수 있다.)
*/
public class ObjectCastingDemo {
public static void main(String[] args) {
Tico t = new Tico();
Sonata so = new Sonata();
//t = (Tico)so; //상속관계가 되어야 가능.
//t = so; //자식은 부모로 자동형변환이 된다.
if(t instanceof Sonata) so = (Sonata)t; //부모--> 자식의 형변환이 되는지 확인하는 instanceof
else System.out.println("안됨");
so = (Sonata)t;
}
}
class Tico{}
class Sonata extends Tico{}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
public class Point {
private int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
@Override
public String toString(){
return String.format("(x,y) = (%d,%d)" , this.x, this.y);
}
@Override
public boolean equals(Object obj){
Point copy = (Point)obj;
if(this.x == copy.x && this.y == copy.y)return true;
else return false;
}
}
public class ObjectCastDemo1 {
public static void main(String[] args) {
ObjectCastDemo1 ocd = new ObjectCastDemo1();
Point p = new Point(100,200);
ocd.print(3,89.5,false,'A', "Hello", p);
}
void print(Object ... array){
for(Object obj : array){
if(obj.getClass().getName().equals("Point")){ //Point 클래스라면
if(obj instanceof Point) System.out.println("가능");
else System.out.println("불가능");
}else{ //Point class 가 아니면
System.out.println(obj); //obj.toString()
}
}
}
}
출력:
3
89.5
false
A
Hello
가능
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
public class Dog extends Mammal {
@Override
public void saySomething(){
System.out.println("멍멍멍멍");
}
}
public class Cat extends Mammal {
@Override
public void saySomething(){
System.out.println("야옹야옹");
}
}
public class Korean extends Mammal {
@Override
public void saySomething(){
System.out.println("안녕하세요.");
}
}
public class American extends Mammal {
@Override
public void saySomething(){
System.out.println("Good Morning");
}
}
public class Mammal {
public void saySomething(){
System.out.println("그냥 운다");
}
}
import java.util.Scanner;
public class PholymorphismDemo {
public static void main(String[] args) {
PholymorphismDemo pd = new PholymorphismDemo();
int choice = 0;
do{
pd.showMenu();
choice = pd.input();
pd.output(choice);
}while(choice != 5 && choice >= 1 && choice < 5);
}
void showMenu(){
System.out.println("****Menu****");
System.out.println("1.Dog");
System.out.println("2.Cat");
System.out.println("3.Korean");
System.out.println("4.American");
System.out.println("5.Exit");
}
int input(){
Scanner scan = new Scanner(System.in);
System.out.println("당신은 어느 종족이십니까?");
int choice = scan.nextInt();
return choice;
}
void output(int choice){
Mammal m = null;
switch(choice){
case 1 : m = new Dog(); break;
case 2 : m = new Cat(); break;
case 3 : m = new Korean(); break;
case 4 : m = new American(); break;
}
m.saySomething();
}
}
출력:
****Menu****
1.Dog
2.Cat
3.Korean
4.American
5.Exit
당신은 어느 종족이십니까?
4
Good Morning
****Menu****
1.Dog
2.Cat
3.Korean
4.American
5.Exit
당신은 어느 종족이십니까?
1
멍멍멍멍
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
'Java & Oracle' 카테고리의 다른 글
AccessModifier, static(variable, method, initializer), final, Deprecation, 중첩클래스4가지, enum, Exception, finally (0) | 2014.03.20 |
---|---|
다형성관계에서 오버라이딩,Polymorphic Parameters, abstract, interface, clone, (classpath,package, jar) (0) | 2014.03.19 |
자바 캡슐화, this, 생성자 (0) | 2014.03.17 |
자바 Encapsulation, split을 이용한 파싱, private (0) | 2014.03.14 |
자바 method,helloworld출력방법8가지,파일입력,...사용, 재귀호출,UML tool 설치 (0) | 2014.03.13 |