본문 바로가기

자바/객체지향

final 키워드 예제) public class Test5 {public static void main(String[] args) {System.out.println(Ex5.x);//Ex5.x=20; //final이므로 오류//System.out.println(Ex5.y); 인스턴스변수임. static이 붙지 않은 변수이므로 바로 사용불가. 사용하려면 객체 생성하여야 한다.(8,9번줄)Ex5 ob=new Ex5();System.out.println(ob.y);// ob.y=90; // final 변수라 2번째 초기화 불가능.ob.write();}} // final class : 하위 클래스(자식)를 가질 수 없다. => 대표적인 final 클래스 : String 클래스final class Ex5{public static .. 더보기
static 키워드 예제1) public class Test3 {public static void main(String[] args) {System.out.println("main:"+Ex3.x);System.out.println("main:"+Ex3.y);//System.out.println("main:"+Ex3.z); //에러.//static 변수가 아닌 경우 반드시 객체 생성후에만 가능Ex3.print(); //Ex3.write(); //에러Ex3 ob = new Ex3();ob.write();}} // static 키워드가 붙은 변수나 메소드는 클래스가 메모리에 로딩됨과 동시에 메모리에 할당되므로 객체를 생성하지 않아도 클래스의 이름으로 바로 접근 가능(Ex3.x)// 클래스 앞에 static 키워드는 내부클래스인 .. 더보기
업캐스팅 다운캐스팅 예제1) public class Test9 {public static void main(String[] args) {// super 생성자(먼저 메모리할당) -> sub 생성자Demo9 ob1=new Demo9(); // new에 의하여 객체생성하면서 생성자 실행System.out.println(ob1.b); // 자기것(30) -> 자기것은 Demo9(하위클래스). ob1.exam(); // 자기것 메소드 실행 Ex9 ob2=ob1; // 업캐스팅 => 변수는 상위클래스것을 쓰고 메서드는 하위에 없으면 상위 것을 쓴다.(재정의가 되어있는 메소드에 한해서) //Ex9 ob4=new Demo9(); // 이것은 객체생성과 동시에 업캐스팅한것이다. // 상위 클래스 객체는 하위 클래스 객체를 가르킬수 있다... 더보기
재정의(override), 중복정의(overloading) 예제) public class Test8 {public static void main(String[] args) {Rect aa=new Rect();Circle bb=new Circle();aa.calc(10, 20);aa.write("사각형 넓이 :");bb.result(10);bb.write("원 넓이 :");}} class Ex8 {protected double area;public void write(String title) {System.out.println(title+area);}} class Rect extends Ex8 {private int w, h;public void calc(int w, int h) {this.w=w;this.h=h;area=(double)this.w*this.h;}.. 더보기
자바의 상속 예제) public class Test7 {public static void main(String[] args) {Demo7 ob=new Demo7();ob.set();ob.write();ob.print();}} class Ex7 {private int a;protected int b;public int c, d;public void print() {System.out.println("a:"+a+",b:"+b+",c"+c+",d:"+d);}} // 자바는 단일 상속만 지원한다.class Demo7 extends Ex7 {public int d;public void set() {// a=10; // supper 클래스의 접근제어자가 private는 접근불가b=20;c=30;d=40;}public void .. 더보기
Method 메서드 예제1) public class Test1 {public static void main(String[] args){ Ex1 oo=new Ex1(); // Ex1 oo; oo=new Ex1; 과 같다 new 다음 생성자.double a=oo.pow(2, 10);// 2,10:실인수pow의 함수 값은 double 이므로 double로 설정System.out.println("2의 10승 : " +a); char aa=oo.upper('b');System.out.println("b:"+aa); System.out.println("b:"+oo.isUpper('b'));System.out.println("A:"+oo.isUpper('A')); int aaa=oo.sum(3,1);System.out.println(".. 더보기
객체지향을 위한 첫걸음 class 클래스 예제1) public class Test1 {public static void main(String[] args) {// 객체생성(인스턴스 생성)Rect ob1=new Rect();Rect ob2=new Rect(); int a,b; ob1.width=10; // 직접 인스턴스변수 적용(속성 변화)ob1.height=5; a=ob1.area(); // 인스턴스를 이용한 변수 적용(속성 변화)b=ob1.len(); ob1.print(a,b); // 메서드 호출(기능 실행) a=ob2.area();b=ob2.len();ob2.print(a,b);}} /*사각형의 넓이와 둘레 계산하는 클래스 작성1. 추상화상태(데이터) : 가로,세로행동(메소드) : 넓이계산,둘레계산,출력2. 클래스작성3. 객체생성*/ cla.. 더보기