추상클래스 Abstract class 인터페이스 Interface 
can have abstract and non-abstract methods.  an have only abstract methods.
doesn't support multiple inheritance. supports multiple inheritance.
can have final, non-final, static and non-static variables. has only static and final variables.
can provide the implementation of interface. can't provide the implementation of abstract class.
An abstract class can extend another class and implement multiple interfaces.  An interface can extend another interface only.
can be extended using keyword "extends" can be implemented using keyword "implements"
can have class members like private, protected, etc.  public by default

ex)

public abstract class Shape{ 
           public abstract void draw(); 
} 

ex)

public interface Drawable{ 
           void draw(); 
}

 

 

 

'java' 카테고리의 다른 글

Java/ 추상화와 추상클래스  (0) 2020.02.28
Java/ ArrayList vs LinkedList  (0) 2020.02.28
Java/ 자료구조 - Array List  (0) 2020.02.28
Java/ 자료구조 - Linked List  (0) 2020.02.28
Java/ Math & Random  (0) 2020.02.28

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details.

Abstraction lets you focus on what the object does instead of how it does it. 

There are two ways to achieve abstraction in java 
- Abstract class (0 to 100%) 
- Interface (100%)

 

 

Abstract class
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body).

Abstract class in Java is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

 

  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have constructors and static methods also.
  • It can have final methods which will force the subclass not to change the body of the method.

 

abstract class Bank{    
abstract int getRateOfInterest();    
}    
class SBI extends Bank{    
int getRateOfInterest(){return 7;}    
}    
class PNB extends Bank{    
int getRateOfInterest(){return 8;}    
}    
    
class TestBank{    
public static void main(String args[]){    
Bank b;  
b=new SBI();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
b=new PNB();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
}}    
Rate of Interest is: 7 %
Rate of Interest is: 8 %

'java' 카테고리의 다른 글

Java/ 인터페이스 vs 추상클래스  (0) 2020.02.28
Java/ ArrayList vs LinkedList  (0) 2020.02.28
Java/ 자료구조 - Array List  (0) 2020.02.28
Java/ 자료구조 - Linked List  (0) 2020.02.28
Java/ Math & Random  (0) 2020.02.28

 

ArrayList  LinkedList
데이터의 검색에 유리 데이터의 검색에 불리
추가, 삭제에 불리 - all the bits are shifted in memory. 

추가, 삭제에 유리 - no bit shifting is required in memory.

internally uses a dynamic array to store the elements.  internally uses a doubly linked list to store the elements.
can act as a list only because it implements List only. 

can act as a list and queue both because it implements List and Deque interfaces. 

=> 공간적 유동성과 비유동성차이

 

 

 

- ex

import java.util.*;    
class TestArrayLinked{    
 public static void main(String args[]){    
     
  List<Name> al=new ArrayList<Name>();//creating arraylist    
  al.add("Lovy");//adding object in arraylist    
  al.add("Elsom");    
  al.add("Dave");    
  al.add("Kris");    
    
  List<Name> ll=new LinkedList<Name>();//creating linkedlist    
  al2.add("James");//adding object in linkedlist    
  al2.add("Serena");    
  al2.add("Jessica");    
  al2.add("Elsa");    
    
  System.out.println("arraylist: "+al);  
  System.out.println("linkedlist: "+ll);  
 }    
}  

'java' 카테고리의 다른 글

Java/ 인터페이스 vs 추상클래스  (0) 2020.02.28
Java/ 추상화와 추상클래스  (0) 2020.02.28
Java/ 자료구조 - Array List  (0) 2020.02.28
Java/ 자료구조 - Linked List  (0) 2020.02.28
Java/ Math & Random  (0) 2020.02.28

Array List 구조

  • 물리적으로 연속적인 구조
  • 순차검색으로는 가장 빠르다.
  • 검색시 운나쁘면 맨뒤까지 검색해야한다 but 인덱스를 알면 바로 찾을수도 있음
  • 삽입시 뒤의 데이터를 1칸씩 뒤로 밀어야함
  • 삭제시 뒤의 데이터를 전부 1칸씩 당겨야함
  • 확장시 공간이 부족하면 더 큰 새 공간을 할당하고 전부 복사해야함
    ->유연성이 떨어짐


Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.

The important points about Java ArrayList class are:

  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.

-ex1

import java.util.*;  
class Book {  
int id;  
String name,author,publisher;  
int quantity;  
public Book(int id, String name, String author, String publisher, int quantity) {  
    this.id = id;  
    this.name = name;  
    this.author = author;  
    this.publisher = publisher;  
    this.quantity = quantity;  
}  
}  
public class ArrayListExample {  
public static void main(String[] args) {  
    //Creating list of Books  
    List<Book> list=new ArrayList<Book>();  
    //Creating Books  
    Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);  
    Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);  
    Book b3=new Book(103,"Operating System","Galvin","Wiley",6);  
    //Adding Books to list  
    list.add(b1);  
    list.add(b2);  
    list.add(b3);  
    //Traversing list  
    for(Book b:list){  
        System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);  
    }  
}  
}  
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

 

 

-ex2

class Human {
	String name;
	int age;

	Human(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return name + ", " + age;
	}
}

public class UseArrayList {
	public static void main(String[] args) {
		
		ArrayList<Human> hList = new ArrayList<Human>();
		hList.add(new Human("장그레이스", 24));
		hList.add(new Human("브리트니 점례", 21));
		hList.add(new Human("저스틴 옥", 21));

		for (Human hu : hList)
			System.out.println(hu);

	}
}

 

'java' 카테고리의 다른 글

Java/ 추상화와 추상클래스  (0) 2020.02.28
Java/ ArrayList vs LinkedList  (0) 2020.02.28
Java/ 자료구조 - Linked List  (0) 2020.02.28
Java/ Math & Random  (0) 2020.02.28
Java/ Interface의 개념  (0) 2020.02.10

링크드리스트=연결리스트

 

: 순서가 있는 데이터 목록

  • 논리적으로 연속된 리스트
  • 필요할 때 공간을 할당  
  • 순차검색은 어레이리스트보다 느리지만 추가, 삽입, 삭제, 확장이 매우 유연하다.
    ->전후 Element만 연결해주면 끝!
  • 데이터의 변화가 심한 데이터구조에 유리

 

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

 

  • Java LinkedList class can contain duplicate elements.
  • Java LinkedList class maintains insertion order.
  • Java LinkedList class is non synchronized.
  • In Java LinkedList class, manipulation is fast because no shifting needs to occur.
  • Java LinkedList class can be used as a list, stack or queue.

 

-ex1

import java.util.*;  
class Book {  
int id;  
String name,author,publisher;  
int quantity;  
public Book(int id, String name, String author, String publisher, int quantity) {  
    this.id = id;  
    this.name = name;  
    this.author = author;  
    this.publisher = publisher;  
    this.quantity = quantity;  
}  
}  
public class LinkedListExample {  
public static void main(String[] args) {  
    //Creating list of Books  
    List<Book> list=new LinkedList<Book>();  
    //Creating Books  
    Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);  
    Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);  
    Book b3=new Book(103,"Operating System","Galvin","Wiley",6);  
    //Adding Books to list  
    list.add(b1);  
    list.add(b2);  
    list.add(b3);  
    //Traversing list  
    for(Book b:list){  
    System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);  
    }  
}  
}  
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

 

 

 

 

-ex2

class Human {
	String name;
	int age;

	Human(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return name + ", " + age;
	}
}

public class UseLinkedList {

	public static void main(String[] args) {

		LinkedList<Human> hList = new LinkedList<Human>();
		hList.add(new Human("장그레이스", 24));
		hList.add(new Human("브리트니 점례", 21));
		hList.add(new Human("저스틴 옥", 21));

		for (Human hu : hList)
			System.out.println(hu);
	}
}

'java' 카테고리의 다른 글

Java/ ArrayList vs LinkedList  (0) 2020.02.28
Java/ 자료구조 - Array List  (0) 2020.02.28
Java/ Math & Random  (0) 2020.02.28
Java/ Interface의 개념  (0) 2020.02.10
Java/ MVC패턴과 추상클래스를 이용한 사원 관리 프로그램  (0) 2020.02.10

Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

 

Unlike some of the StrictMath class numeric methods, all implementations of the equivalent function of Math class can't define to return the bit-for-bit same results. This relaxation permits implementation with better-performance where strict reproducibility is not required.

 

If the size is int or long and the results overflow the range of value, the methods addExact(), subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException.

For other arithmetic operations like increment, decrement, divide, absolute value, and negation overflow occur only with a specific minimum or maximum value. It should be checked against the maximum and minimum value as appropriate.

public class UseMath {
	public static void main(String[] args) {
		System.out.println(Math.PI);
		System.out.println(Math.sqrt(2));	// 제곱근
		System.out.println(Math.toDegrees(Math.PI)); // 각도
		System.out.println(Math.toDegrees(Math.PI * 2.0));
		double radian45 = Math.toRadians(45);	// 라디안
		System.out.println(Math.sin(radian45));
		System.out.println(Math.cos(radian45));
		System.out.println(Math.tan(radian45));
		System.out.println(Math.log(25));
		System.out.println(Math.pow(2, 4));	// 제곱
	}
}

 

 

 

Java Random class is used to generate a stream of pseudorandom numbers. The algorithms implemented by Random class use a protected utility method than can supply up to 32 pseudorandomly generated bits on each invocation.

public class UseRandom {
	public static void main(String[] args) {
		Random rand = new Random();
		
		for(int i=0;i<10;i++)
			System.out.print(rand.nextInt(100) + ", ");// 0 ~ 99
		System.out.println();
		//Math.random();// 0.0이상 ~ 1.0미만 실수
		for(int i=0;i<10;i++)
			System.out.print((int)(Math.random()*100) + ", ");// 0 ~ 99
		System.out.println();
	}
}
​

 

 

Interface is a blueprint of a class. It has static constants and abstract methods.

The interface is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.

Why use Java interface?

  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

 

인터페이스의 생김새는 클래스와 유사하지만 객체를 만들 수 없다. 그러나 인터페이스 형 변수와 배열은 선언 할 수 있다.  인터페이스와 이를 이용한 클래스를 사용하면 이해하기 쉬운 코드를 작성 할 수 있다. 

 

- Literal 상수 : 숫자 1, 2, ...
- Constant 상수 : 변수 -> 상수(final) MON, TUE, ...
-인터페이스에 선언하는 필드는 자동으로 public final static이 붙는다.

 

public class SelectDayWeek {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("오늘의 요일을 선택하세요");
		System.out.println("1.월요일, 2.화요일, 3.수요일");
		System.out.println("4.목요일, 5.금요일, 6.토요일");
		System.out.println("7.일요일");
		System.out.print("번호 선택 : ");
		int sel = sc.nextInt();
		switch(sel) {
		case IWeek.MON:System.out.println("주간회의 있습니다");break;
		case IWeek.TUE:System.out.println("플젝회의 있습니다");break;
		case IWeek.WED:System.out.println("진행보고 있습니다");break;
		case IWeek.THU:System.out.println("축구시합 있습니다");break;
		case IWeek.FRI:System.out.println("플젝발표 있습니다");break;
		case IWeek.SAT:System.out.println("가족여행 떠납니다");break;
		case IWeek.SUN:System.out.println("오늘은 휴일입니다");break;			
		}
		
		sc.close();
	}
}
public interface IWeek{
	int MON=1, TUE=2, WED=3, THU=4, FRI=5, SAT=6, SUN=7;
}

enum(열거형)으로도 사용가능

/* 
public class IWeek { 
public final static int MON = 1; 
public final static int TUE = 2; 
public final static int WED = 3; 
public final static int THU = 4; 
public final static int FRI = 5; 
public final static int SAT = 6; 
public final static int SUN = 7; 
} 
*/

 

 

 

 

 

-ex

interface Bank{  
float rateOfInterest();  
}  
class SBI implements Bank{  
public float rateOfInterest(){return 9.15f;}  
}  
class PNB implements Bank{  
public float rateOfInterest(){return 9.7f;}  
}  
class TestInterface2{  
public static void main(String[] args){  
Bank b=new SBI();  
System.out.println("ROI: "+b.rateOfInterest());  
}} 
ROI: 9.15

- 추상클래스의 특징
1) 추상메서드를 한 개 이상 포함하고 있다.
2) 추상메서드는 구현이 되지않은 메서드이다.
3) 추상클래스는 객체를 만들수 없다.
4) 추상클래스를 상속받은 자식클래스가  추상메서드를 구현하지않으면 자식 클래스도 추상 클래스가 된다.

- 추상클래스의 목적
1) 추상 메서드에서는 필드와 메서드를 정의 할 수 없다. (상속만 가능) 자식클래스로 하여금 구현을 강요하도록 한다.
2) 부모인 추상클래스 변수를 통해 매개 변수로 전달하여 메서드의 양을 줄이는 효과가 있다.
3) 부모 추상클래스 변수의 배열에 자식 클래스들의 객체들을 담아서 각각 다른 클래스 객체를 통일성있게 관리할 수 있다.

 

 

 

Main class

public class Main {
	public static void main(String[] args) {
		View view=new View(); 
		view.menuLoop();
	}
}

 

 

 

Model
상속을 전제로한 추상클래스.
사원의 종류에 따라 급여가 다르게 구현되도록 추상클래스와 추상메서드를 사용하였다.

public abstract class Employee {
	protected String emNum;
	protected String name;
	protected double pay;
	
	public Employee(String emNum, String name, double pay) {
		this.emNum=emNum;
		this.name=name;
		this.pay=pay;
	}
	
	public void showEmployeeInfo() {
		System.out.println("사번: " + emNum);
		System.out.println("이름: " + name);
		System.out.println("급여: " + pay);
	}
	
	
	//
	public abstract double getMonthPay();

	public void showMonthPayInfo() {
		
		System.out.println("급여: "+pay);
	}
	
}
public class FullEmployee extends Employee {
	protected double bonus;
	
	public FullEmployee(String emNum, String name, double pay, double bonus) {
		super(emNum, name, pay);
		this.bonus=bonus;
		
	}

	public void showEmployeeInfo(){
		super.showEmployeeInfo();
		System.out.println("보너스:"+ bonus);
	}
	
	public double getMonthPay() {
		return (pay/12+bonus/12);
	}
}
public class ContracEmployee extends Employee {
	private int hiredYear;
	
	public ContracEmployee(String emNum, String name, double pay, int hiredYear) {
		super(emNum,name,pay);
		this.hiredYear=hiredYear;
	}
	public void showEmployeeInfo(){
		super.showEmployeeInfo();
		System.out.println("입사년도:"+ hiredYear);
	}
	
	public double getMonthPay() {
		return pay/12;
	}
}
public class TempEmployee extends Employee {
	protected double workDay;
	
	public TempEmployee(String emNum, String name, double pay, double workDay) {
		super(emNum,name,pay);
		this.workDay=workDay;
	}
	
	public void showEmployeeInfo() {
		super.showEmployeeInfo();
		System.out.println("출근일: "+workDay);
	}
	
	public double getMonthPay() {
		return pay/12/20*workDay;
	}
}

 

 

 

View

class MENU {
	final static int FULL = 1;
	final static int CONTRACT = 2;
	final static int TEMP = 3;
	final static int SHOW_ALLDATA = 4;
	final static int GET_MONTHPAY = 5;
	final static int EXIT = 6;
//메뉴라는 클래스를 설정해서 상수에 이름 을 붙혀서 가독성이 더좋아졌다, 
}

public class View {
	static Scanner sc = new Scanner(System.in);

	Controller controller;

	public View() {

		int num = getEmployeeNum();
		controller = new Controller(num);
	}

	public static Scanner getScanner() {
		return sc;
	}

	int getEmployeeNum() {
		System.out.println("몇명의 사원의 정보를 입력하시겠습니까?");
		int num = sc.nextInt();
		return num;
	}

	void viewMenu() {
		System.out.println("----메뉴 선택----");
		System.out.println("1. 정규직 저장");
		System.out.println("2. 계약직 저장");
		System.out.println("3. 임시직 저장");
		System.out.println("4. 전체 정보 출력");
		System.out.println("5. 월급 계산 출력");
		System.out.println("6. 프로그램 종료");
	}

	int getUserSel() {
		System.out.println("선택>>");
		int selNum = sc.nextInt();
		return selNum;

	}

	boolean runSel(int selNum) {//숫자를 쓰는 대신에 단어로 바꿔서 더읽기쉽게 가독성을 높혔습니다.
		switch (selNum) {
		case MENU.FULL:
			System.out.println("--정사원정보저장--");
			controller.addEmp(selNum);
			break;
		case MENU.CONTRACT:
			System.out.println("--계약사원정보저장--");
			controller.addEmp(selNum);
			break;
		case MENU.TEMP:
			System.out.println("--임시사원정보저장--");
			controller.addEmp(selNum);
			break;
		case MENU.SHOW_ALLDATA:
			System.out.println("--모든직원정보보기--");
			controller.showEmployeeInfo();
			break;
		case MENU.GET_MONTHPAY:
			System.out.println("--급여정보보기--");
			controller.showMonthPay();
			break;
		case MENU.EXIT:
			System.out.println("--프로그램종료--");
			return false;
		default:
			System.out.println("오류");
			break;
		}
		return true;
	}

	void menuLoop() {
		boolean isRun = true;
		while (isRun) {
			viewMenu();
			int selNum = getUserSel();
			isRun = runSel(selNum);

		}
	}

}

 

 

 

Controller

화면에서 사용자의 선택에 대한 처리 기능들의 역할
- 처리를 담당하는 클래스
- (비지니스 로직을 담당)
- Controller
- Service
- Manager
- Handler

public class Controller {

	private Employee[] myEmp;
	private int numOfEmp;
	private final static int EMP_NUM = 200;

	public Controller() {
		myEmp = new Employee[EMP_NUM];
		numOfEmp = 0;
	}

	public Controller(int num) {
		myEmp = new Employee[num];
		numOfEmp = 0;
	}

	void addEmpInfo(Employee emp) {
		if (numOfEmp < myEmp.length)
			myEmp[numOfEmp++] = emp;
		else
			System.out.println("저장공간이 부족합니다.");
	}

	void addEmp(int selNum) {
		String emNum, name;
		int pay, bonus, hiredYear, workDay;

		Scanner sc = View.getScanner();
		System.out.println("사번: ");
		emNum = sc.next();
		System.out.println("이름: ");
		name = sc.next();
		System.out.println("연봉: ");
		pay = sc.nextInt();

		if (selNum == MENU.FULL) {
			System.out.println("보너스:");
			bonus = sc.nextInt();
			addEmpInfo(new FullEmployee(emNum, name, pay, bonus));
		} else if (selNum == MENU.CONTRACT) {
			System.out.println("입사년도: ");
			hiredYear = sc.nextInt();
			addEmpInfo(new ContracEmployee(emNum, name, pay, hiredYear));
		} else if (selNum==MENU.TEMP) {
			System.out.println("출근일수: ");
			workDay=sc.nextInt();
			addEmpInfo(new TempEmployee(emNum, name, pay,workDay));
			}
	}

	void showEmployeeInfo() {
		for (int i = 0; i < numOfEmp; i++) {
			myEmp[i].showEmployeeInfo();
			System.out.println();
		}

	}

	void showMonthPay() {
		for (int i = 0; i < numOfEmp; i++) {
			System.out.println((i+1)+"번 째 사원의 월급은 "+myEmp[i].getMonthPay()+"만원 입니다.");
		}
	}

}

'java' 카테고리의 다른 글

Java/ Math & Random  (0) 2020.02.28
Java/ Interface의 개념  (0) 2020.02.10
Java/ MVC패턴과 추상클래스를 이용한 연락처 관리 프로그램  (0) 2020.02.10
Java/ equals와 toString의 사용  (0) 2020.02.10
Java/ 상속  (0) 2020.02.10