중첩 클래스와 중첩 인터페이스 소개

중첩 클래스란 클래스 내부에 선언한 클래스를 말한다. 중첩 클래스를 사용하면 두 클래스의 멤버들을 서로 쉽게

접근할 수 있고, 외부에는 불필요한 관계 클래스를 감춤으로써 코드의 복잡성을 줄일 수 있다는 장점이 있다.

package sec01.exam04;

public class Test {
	
	class NestedClass { // 중첩 클래스
		
	}
}

 

인터페이스도 클래스 내부에 선언할 수 있는데, 이런 인터페이스를 중첩 인터페이스라고 한다.

인터페이스를 클래스 내부에 선언하는 이유는 해당 클래스와 긴밀한 관계를 맺는 구현 클래스를 만들기 위해서

package sec01.exam04;

public class Test {
	
	interface NestedInterface { // 중첩 인터페이스
		
	}
}

 

 

중첩 클래스

중첩 클래스는 클래스 내부에 선언되는 위치에 따라서 두 가지로 분류한다.

1. 멤버 클래스 : 클래스의 멤버로서 선언되는 중첩 클래스를 멤버 클래스라고 한다.

   - 멤버 클래스는 클래스나 객체가 사용 중이라면 언제든지 재사용이 가능하다.

 

2. 로컬 클래스 : 생성자 또는 메소드 내부에서 선언되는 중첩 클래스를 로컬 클래스라고 한다.

   - 로컬 클래스는 메소드를 실행할 때만 사용되고 메소드가 종료되면 없어 진다.

 

인스턴스 멤버 클래스

인스턴스 멤버 클래스는 static 키워드 없이 중첩 선언된 클래스

인스턴스 필드와 메소드만 선언이 가능하고 정적 필드와 메소드는 선언할 수 없다.

일반적으로 A클래스 외부에서 B객체를 생성하는 일은 거의 없음

 

정적 멤버 클래스

정적 멤버 클래스는 static 키워드로 선언된 클래스를 말함

정적 멤버 클래스는 모든 종류의 필드와 메소드를 선언할 수 있다.

A 클래스 외부에서 정적 멤버 클래스 C의 객체를 생성하기 위해서는 A객체를 생성할 필요가 없고

밑에 처럼 C 객체를 생성하면 됨

로컬 클래스

중첩 클래스는 메소드 내에서도 선언할 수 있는데, 이것을 로컬 클래스라고 한다.

로컬 클래스 내부에는 인스턴스 필드와 메소드만 선언할 수 있고 정적 필드와 메소드는 선언할 수 없음

 

바깥 필드와 메소드에서 사용 제한 

바깥 클래스에서 인스턴스 멤버 클래스를 사용할 때 제한이 있다.

 

 

 

 

 

멤버 클래스에서 사용 제한 

멤버 클래스가 인스턴스 또는 정적으로 선언됨에 따라 멤버 클래스 내부에서 바깥 클래스의 필드의 필드와

메소드에 접근할 때에도 제한이 따름

 

 

로컬 클래스에서 사용 제한

매개 변수와 로컬 변수를 로컬 클래스 내부에서 사용할 때 매개변수와 로컬 변수가 final 특성을 갖게 됨 ( 변경 불가 )

package sec01.exam04;


// 로컬 클래스에서 사용 제한
public class Outter {
	
	public void method2(int arg) {
		int localVariable = 1;// 로컬 클래스 
//		arg = 100; // final 특성을 갖음 
//		localVariable = 100;
		class Inner {
			public void metod() {
				int result = arg + localVariable;
			}
		}
	}
}

 

 

중첩 클래스에서 바깥 클래스 참조 얻기

선언

package sec01.exam04;

public class Outter2 {
	String field = "Outter=field";
	void method() {
		System.out.println("Outter-method");
	}
	
	class Nested {
		String field = "Nested-method";
		void method() {
			System.out.println("Nested-method");
		}
		
		void print() {
			System.out.println(this.field);
			this.method();
			System.out.println(Outter2.this.field);
			Outter2.this.method();
		}
	}
}


실행

package sec01.exam04;

public class OutterEX {

	public static void main(String[] args) {
		Outter2 outter2 = new Outter2();
		Outter2.Nested nested = outter2.new Nested();
		nested.print();

	}

}
<결과>
Nested-method
Nested-method
Outter=field
Outter-method

 

 

 

중첩 인터페이스

class A {
 [static] interface I {
 	void method();
 	}
 }

중첩 인터페이스는 클래스의 멤버로 선언된 인터페이스를 말한다.

중첩 인터페이스는 인스턴스 멤버 인터페이스와 정적 멤버 인터페이스 모두 가능 하다.

인스턴스 멤버 인터페이스는 바깥 클래스의 객체가 있어야 사용 가능하고,

정적 멤버 인터페이스는 바깥 클래스의 객체 없이 바깥 클래스만으로 바로 접근할 수 있다.

주로 정적 멤버 인터페이스를 많이 사용하는데 UI 프로그래밍에서 이벤트를 처리할 목적으로 많이 활용

 

예) Button을 클릭했을 때 이벤트를 처리하는 객체를 받고 싶다고 가정, 그렇다고 아무 객체나 받으면 안되고

Button 내부에 선언된 중첩 인터페이스를 구현한 객체만 받아야 한다면 밑에 처럼 코딩

중첩 인터페이스

package sec01.exam05;

public class Button {
	// 인터페이스 타입 필드
	OnClicListener listener;
	
	// 매개변수의 다형성
	void setOnClicListener(OnClicListener listener) {
		this.listener = listener;
	}
	
	// 구현 객체의 onClick() 메소드 호출
  	void touch() {
		listener.onClick();
	}
	
	// 중첩 인터페이스
	static interface OnClicListener {
		void onClick();
	}
}


구현 클래스 1

package sec01.exam05;

public class CallListener implements Button.OnClicListener{

	@Override
	public void onClick() {
		System.out.println("전화를 겁니다.");
		
	}

}


구현 클래스 2

package sec01.exam05;

public class MessageListener implements Button.OnClicListener{

	@Override
	public void onClick() {
		System.out.println("메시지를 보냅니다.");
		
	}

}


버튼 이벤트 처리 ( 실행 )

package sec01.exam05;

public class ButtonEx {

	public static void main(String[] args) {
		Button btn = new Button();
		
		btn.setOnClicListener(new CallListener());
		btn.touch();
		
		btn.setOnClicListener(new MessageListener());
		btn.touch();
	}

}
<결과>
전화를 겁니다.
메시지를 보냅니다.

 

 

 

 

익명 객체

익명 객체는 이름이 없는 객체를 말한다. 익명 객체를 만들려면 조건이 있는데 어떤 클래스를 상속하거나

인터페이스를 구현해야만 한다. 일반적인 경우 다음과 같이 명시적으로 클래스 이름을 주고 선언한다.

위에 상속, 구현이 일반적인 경우

밑에 익명객체를 생성할 때 경우

인터페이스

package sec02.exam01;

public interface Iaa {
	void method();
}

class Cbb implements Iaa {

	@Override
	public void method() {
		
		
	}
	
}


실행

package sec02.exam01;

public class Ex1 {

	public static void main(String[] args) {
		Cbb a1 = new Cbb(); // 일반적인 방법
		
		Iaa a2 = new Iaa() { // 익명의 객체 생성
			
			@Override
			public void method() {
				
				
			}
		};

	}

}

 

 

익명의 객체 생성 

인터페이스

package sec02.exam03;

public interface Animal {
	void sound();
}


인터페이스 이용

package sec02.exam03;

// 인터페이스 이용

public class Driver {
	void drive(Animal animal) {
		animal.sound();
	}
}


구현 객체

package sec02.exam03;

public class Dog implements Animal {

	@Override
	public void sound() {
		System.out.println("멍멍");
		
	}

}


실행

package sec02.exam03;

public class AniEx {

	public static void main(String[] args) {
		// 구현 객체 호출
		Dog d1 = new Dog();
		d1.sound();
		
		Driver driver = new Driver();
		driver.drive(d1);
		
		//익명의 객체 생성으로 고양이 소리가 나오게 하세요.
		Animal cat = new Animal() {
			
			@Override
			public void sound() {

				System.out.println("야옹");
				
			}
		}; cat.sound();
		
		// 익명의 객체 다른 호출 방법
		driver.drive(new Animal() {
			
			@Override
			public void sound() {
				System.out.println("야옹");
				
			}
		});
		
	}

}

 

 

익명의 객체 생성 2

UI 클래스

package sec02.exam04;

public class Button {
	
	// UI 클래스
	
	// 인터페이스 타입 필드
	onClickListener listener; // 버튼에 리스너 등록
	
	// Setter // 매개 변수의 다형성
	public void setListener(onClickListener listener) {
		this.listener = listener;
	}
	
	// 구현 객체의 onClick() 메소드 호출
	void touch() {
		listener.onClick();
	}

	// 중첩 인터페이스 
	static interface onClickListener { 
		void onClick();
	}
}


구현객체

package sec02.exam04;

// 구현 객체
public class CallListener implements Button.onClickListener {

	@Override
	public void onClick() {
		System.out.println("전화를 겁니다.");
		
	}

}


실행

package sec02.exam04;

public class ButtonEx {

	public static void main(String[] args) {
		Button bt = new Button();
		bt.setListener(new CallListener());
		bt.touch();
	}

}
<결과>
전화를 겁니다.

 

익명의 객체 생성 3

UI 클래스

package sec02.exam04;

//UI 클래스

public class Window {
	// 버튼 2개 생성
	Button button1 = new Button();
	Button button2 = new Button();
	
	// 버튼 마다 기능 부여 
	public Window() {
		button1.setListener(new Button.onClickListener() {
			
			@Override
			public void onClick() {
				System.out.println("메시지를 보내다.");
				
			}
		});// 메시지
		
		
	}
	
}


실행

package sec02.exam04;

public class WinEx {

	public static void main(String[] args) {
		Window w = new Window();
		w.button1.touch();
		// 메시지를 보낸다 출력하기
		
		// 전화를 겁니다 출력하기
		w.button2.setListener(new Button.onClickListener() {
			
			@Override
			public void onClick() {
				System.out.println("전화를 겁니다.");
				
			}
		});
		w.button2.touch();
		

	}

}
<결과>
메시지를 보내다.
전화를 겁니다.

 

Maria DB 연결 ( insert ) DB에 추가_JAVA

package maria0612;


import java.sql.Connection; //  JDBC 연결
import java.sql.DriverManager; // 데이터베이스 드라이버를 등록하고 연결을 관리
import java.sql.ResultSet;
import java.sql.SQLException; // JDBC에서 발생하는 예외를 처리
import java.sql.Statement; // SQL 문을 실행하기 위해 사용
import java.util.Scanner;

public class JdbcEx {
	
	

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		Connection con = null;
		Statement stmt = null; // insert, select 등의 명령을 위한 변수
		ResultSet rs = null; // select 후에 자료를 메모리에 받아오는 변수
		String url = "jdbc:mariadb://localhost:3307/jspdb";
		String user = "root";
		String pass = "maria";
		Class.forName("org.mariadb.jdbc.Driver");// add throws ClassNotFoundException
		System.out.println("드라이버 로딩!");
		
		con = DriverManager.getConnection(url, user, pass);
		System.out.println("접속 성공!");
		
		Scanner sc = new Scanner(System.in);
		System.out.print("이름 입력=>");
		String name = sc.nextLine();
		System.out.print("주소 입력=>");
		String addr = sc.nextLine();
		System.out.print("전화번호 입력=>");
		String phone = sc.nextLine();
		
		
		
		String sql = "insert into person(name, addr, phone ) values"
					+"('"+name+"','"+addr+"','"+phone+"')";
		 stmt = con.createStatement();
		 int ret = stmt.executeUpdate(sql);
		 System.out.printf("%d 건 입력!\n", ret);
	}

}

 

Maria DB 연결 ( Select ) DB에 테이블 검색_JAVA

package maria0612;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class SelectEx {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		Connection con = null;
		Statement stmt = null; // insert, select 등의 명령을 위한 변수
		ResultSet rs = null; // select 후에 자료를 메모리에 받아오는 변수
		String url = "jdbc:mariadb://localhost:3307/jspdb";
		String user = "root";
		String pass = "maria";
		Class.forName("org.mariadb.jdbc.Driver");// add throws ClassNotFoundException
		System.out.println("드라이버 로딩!");
		
		con = DriverManager.getConnection(url, user, pass);
		System.out.println("접속 성공!");
		
		Scanner sc = new Scanner(System.in);
		System.out.print("검색=>");
		String search = sc.nextLine();
		
		String sql = "select * from person where name like '%"+search+"%'";
		stmt = con.createStatement();
		rs = stmt.executeQuery(sql); // select의 경우만
		while(rs.next()) { //  next() id 1번부터 출력 됨 
			int id = rs.getInt("id");
			String name = rs.getString("name");
			String addr = rs.getString("addr");
			String phone = rs.getString("phone");
			System.out.printf("%d, %s, %s, %s\n", id, name, addr, phone);
			
		}
		

	}

}

 

김씨만 출력 / 특정 검색어 검색 가능

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

2023-06-14 19일차  (0) 2023.06.14
2023-06-13 18일차  (0) 2023.06.13
2023-06-09 16일차  (0) 2023.06.09
2023-06-08 15일차  (0) 2023.06.08
2023-06-07 14일차  (0) 2023.06.07

+ Recent posts