다중 구현(?)

다중 상속은 아래와 같은 모양입니다.
1269519728.bmp
이 때.. 대체 저 자식 클래스는 대체 아빠 엄마 중 누구의 댄스를 따라 출 것이란 말인가..
C++ 에서는 둘 중에 하나를 명시 해서 사용한다고 했던거 같은데 내 영역 바깥의 이야기라 말 안하는게 좋을 듯 합니다.

그런데 Java는 다중 상속이 아예 안되니까 저런 문제를 고민 안해도 될 것 같지만… 오산이라는거~

두 가지 경우가 있다고 생각합니다.
다이어그램을 보면서 이야기 해야 편할 듯 합니다.

1372970978.bmp
에러가 나지 않을 것으로 예상합니다. 그리고 Test 클래스는 당연히 SubClass에서 overring한 dance를 호출하게 될 것입니다.
하지만… 이게 정말 제대로 된건가… 의심이 된다. 부모 Class에 있는 dance를 재정의 하고 싶기도 하고..Dancible 인터페이스를 구현하고 싶을 수도 있을 것입니다. 그럼 dance() 메소드는 두 개가 되어야 하는거 아닌가요?? 메소드 이름이 같으면 할 일이 같다는 말은 되긴 하지만…그래도… 이상한데~

코딩을 해본 결과.. 예상과 일치했습니다.

또하나 다른 경우는 이제 예상이 되시겠지만, 아래와 같은 경우입니다.

1271408834.bmp
이 때도 역시 코드로 확인해 본 결과 에러가 발생하지 않습니다. 당연히.. 양쪽 인터페이스의 제약인 dance() 메소드를 구현해 줬기 때문에 별 탈 없이 돌아가지요. 하지만… ClunMania 인터페이스를 사용하는 나이트 클럽 클래스에서 춤을 추라고 시켰더니..탈춤을 추는 사태가 벌어 질 수도 있겠군요… 이거 어떻게 되는거죠?

모르겠군요.. ㄷㄷㄷ…

Interface

Java Tutorial에 있는 interface부분을 읽으며 정리했던 내용입니다.
원래 엠파스 블러그에 정리해 두었었는데 이번 기회에 이것도 이리 옮겨오네요 🙂

Interface는 다른 class들로 부터 구현될 행동들의 규약을 정의한 것이다.
Interface는 구현되어 있진 않은 메소드 정의들의 집합이다.
abstract class와의 차이점
1. abstract class는 method를 몇개 구현해 놓을 수 있지만 interface는 그렇치 않다.
2. 하나의 class는 여러 interface들을 구현할 수 있지만 (abstract) class는 하나만 상속 받을 수 있다.
3. interface는 2번과 같은 이유로 인해 class hierarchy에 속하지 않는다.
4. 전혀 상관 없는 class들도 같은 interface는 구현할 수 있다.

public
interface InterfaceName extends SupreInterfaces {
        ….
}
interface앞에 붙을 수 있는 접근 지시자는 public과 default(아무것도 안쓰는것)이다.
default의 경우 같은 패키지 안에 있는 class에서만 구현 할 수 있다.
interface는 다중 상속이 가능하다. 물론 interface만 상속 해야한다.
method들은 head부분만 쓰고 쎄미콜론으로 닫아야 한다.
자동으로 public abstarc의 키워드가 붙은것으로 간주하기에 안쓰는게 좋다.
특히 abstract는
필드도 넣을 수 있는데 암것도 안쓰면 자동으로 public static final로 간주한다.
private이나 protected 멤버는 선언할 수 없다.
그리고 멤버의 head에 transient, volatile, synchronized 키워드를 사용할 수 없다.
public class ImplClass extends JFrame implements SuperInterface1, SuperInterface2 {
      …
}
interface를 구현하는 class에서는 여러 interface를 implements 할 수 있다.
이 것은 interface와의 이종의 계약이다. interface에 들어있는 모든 method를 구현하겠다는..
만약 이 약속을 지키지 않을 시 이 class는 abstract class가 되어야 한다.

interface type의 객체는 만들 수 없지만 변수는 만들 수 있다.

이 변수로 해당 interface를 구현한 class들의 객체를 참조 할 수 있다.

끝으로
이미 interface가 있고 그리고 그 interface를 구현한 class들이 있느 상태에서

interface에 새로운 메소드를 추가하는 가능하면 하지 말아야 한다.

그 interface를 구현한 모든 class들에서 에러가 발생할 것이다.

모든 calss들을 들려서 추가한 method를 구현해 주거나 class들을 abstract class로 만들어야 한다.
이럴바엔 차라리 새로운 interface는 만들어서 필요한 class들이 추가로 implement 하게 수정하는게 좋다.

Lesson 3. Strings and Packages

Lesson 3. Strings and Packages

이번 장에서 배울 내용:

  • String 클래스에 대해 좀더 알아보고
  • Java에서 문자들을 어떻게 다루는지
  • 플랫폼 독립적인 코드를 확인하기 위해 시스템 속성 사용하기
  • 문자열을 동적으로 만들기 위해 StringBuffer 객체 사용하기
  • collection에 있는 각각의 객체들 순회하기
  • System.out 사용해서 출력하기
  • class들을 패키지로 조직화 하기
  • public과 private 접근 지시자 이해하기

Characters and Strings

While Strings are objects, they are made up of sequences of individual characters. Java represents a character as a primitive type known as char. Since a char value is of a primitive type (like an int value), remember that you cannot send messages to it.

Java includes a char type that represents letters, digits, punctuation marks, diacriticals, and other special characters.

Java uses two bytes to store each character.

Special Characters

‘\r’ ‘\n’ ‘\t’ ‘\f’ ‘\b’ ‘\” ‘\\’ ‘\”‘

Strings

A String object represents a sequence of char values of fixed length.

You can construct Strings in a number of ways. Any time you create a new String literal, the Java VM constructs a String object behind the scenes. Here are two ways to construct a String object and assign it to a reference variable:

[CODE]

String a = “abc”;

String b = new String(“abc”); // DON’T DO THIS

[/CODE]

Since strings are sequences of characters, they can embed special characters.

String z = “\t\n”;

you will notice that there are no methods that change a string. You cannot alter the length of a string, nor can you alter any of the characters contained within a string. String objects are thus immutable. If you want to perform any manipulations on a string, you must create a new string.

System Properties

The System class contains a method named getProperty that takes a system property key (a String) as a parameter and returns the system property value associated with the key. The Java VM sets several system properties upon startup. Many of these properties return information about the VM and execution environment. The API documentation method detail for getProperties shows the list of available properties.

getProperties

public static Properties getProperties()
Determines the current system properties.

First, if there is a security manager, its checkPropertiesAccess method is called with no arguments. This may result in a security exception.

The current set of system properties for use by the getProperty(String) method is returned as a Properties object. If there is no current set of system properties, a set of system properties is first created and initialized. This set of system properties always includes values for the following keys:

Key Description of Associated Value
java.version Java Runtime Environment version
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
java.ext.dirs Path of extension directory or directories
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator (“/” on UNIX)
path.separator Path separator (“:” on UNIX)
line.separator Line separator (“\n” on UNIX)
user.name User’s account name
user.home User’s home directory
user.dir User’s current working directory

Multiple paths in a system property value are separated by the path separator character of the platform.

Note that even if the security manager does not permit the getProperties operation, it may choose to permit the getProperty(String) operation.

Returns:

the system properties

Throws:

SecurityException – if a security manager exists and its checkPropertiesAccess method doesn’t allow access to the system properties.

See Also:

setProperties(java.util.Properties), SecurityException, SecurityManager.checkPropertiesAccess(), Properties

Looping through Collections

What you would like to be able to do is to execute the same three lines of code for each of the students in the ArrayList, regardless of how many students the ArrayList contains. There are several ways of doing this in Java. The most straightforward means in J2SE 5.0 is to use a for-each loop.

[CODE]

for (Student student: students) {

   // … statements here …

}

[/CODE]

Single-Responsibility Principle
One of the most basic design principles in object-oriented programming is that a class should do one thing and do it well. By virtue of doing this one thing, the class should have only one reason to change. This is known as the Single-Responsibility Principle.

System.out

Java provides output facilities to allow you to redirect information to the console, to files, and to other destinations. You will learn about these output facilities in depth in Lesson 11.

You will see that out is a static variable, of the type PrintStream, that represents the standard output stream, also known as stdout or simply “the console.” You can directly access this console object using the following static variable reference: System.out

Access Modifier

The public and private keywords are known as access modifiers. You use access modifiers to control access to Java elements, including fields, methods, and classes. The access modifiers that are appropriate for a class are different than those that are appropriate for methods and fields.

By declaring a class as public, you allow classes in other packages to be able to import and refer directly to the class.

Using Ant

Ant is a platform-independent tool that allows you to create specifications of how your project should be built and deployed.

Other alternatives are to build a shell script or batch file as I demonstrated in Lesson 1. You can also use one of a number of available make tools. A make tool is a build tool very similar to Ant, but most make tools are very tightly bound to a specific operating system. Few make tools provide the ease of building Java applications that Ant does. Ant is the most effective way of doing builds in Java.

Lesson 2. Java Basics

Lesson 2. Java Basics

이번장에서 배우게 될 내용은:

  • 학생수를 세기 위한 int 형 변수 사용하기
  • 여러 학생을 저장하기 위한 ArrayList 사용하기
  • 기본 생성자 이해하기
  • ArrayList를 어떻게 사용하는지 이해하기 위해 J2SE API를 어떻게 사용하는지 배우기
  • Student 객체만을 담기 위해 ArrayList를 제약하기
  • 여러 class를 test하기 위한 TestSuite 만들기
  • 패키지를 이해하고 import문을 배우기
  • 상수를 정의하는 방법과 사용
  • 시스템 라이브러리의 date와 calandar 클래스 사용하기
  • Java가 허용하는 다양한 주석문 배우기
  • javadoc을 사용하여 API 문서 생성하기

int

The int type allows variables to be created that store integer values from -2,147,483,648 to 2,147,483,647.

Numbers in Java are not objects like String literals are. You cannot send messages to numbers, although numbers can be passed as parameters along with messages just like Strings can. Basic arithmetic support in Java is provided syntactically; for many other operations, support is provided by system libraries. You will learn about similar non-object types later in Agile Java. As a whole, these non-object types are known as primitive types.

Initialization

you have two ways to initialize fields: You can initialize at the field level or you can initialize in a constructor.

There is no hard-and-fast rule about where to initialize. I prefer initializing at the field level when possiblehaving the initialization and declaration in one place makes it easier to follow the code. Also, as you will learn later in this lesson, you can have more than one constructor; initializing at the field level saves you from duplicate initialization code in each constructor.

Default Constructor

If you do not define any constructors in a class, Java provides a default, no-argument constructor.

The use of default constructors also implies that Java views constructors as essential elements to a class. A constructor is required in order for Java to initialize a class, even if the constructor contains no additional initialization code. If you don’t supply a constructor, the Java compiler puts it there for you.

Suites

여러 클래스들을 한꺼번에 테스트하고 싶을 때 다음과 같이 suite을 생성하여 추가합니다.


위 그림은 JUnit 3.8 대의 사용 법.
아래 그림은 JUnit 4.1에서 annotation을 사용 하는 방법.

The SDK and java.util.ArrayList

java.util.ArrayList<Student> allStudents = session.getAllStudents();

A type appearing in this forma class name followed by a parameter type within angle brackets (< and >) is known as a parameterized type. In the example, the parameter Student of java.util.ArrayList indicates that the java.util.ArrayList is bound such that it can only contain Student objects.

The class java.util.ArrayList is one of thousands available as part of the Java SDK class library.

왼쪽 상당은 패키지, 왼쪽 하단은 해당 패키지에 속한 클래스들 오른쪽은 하나의 클래스에 대한 설명을 보여주는 3단 구조로 되어있다.

Objects In Memory


사실 “Cain DiVoe” 같은 문자열도 메모리 어딘가를 참조하는 변수 일 텐데 그것은 그림에 빠져있다.

Packages and the import Statement

Packages provide a way for developers to group related classes. They can serve several needs: First, grouping classes into packages can make it considerably easier on developers, saving them from having to navigate dozens, hundreds, or even thousands of classes at a time. Second, classes can be grouped into packages for distribution purposes, perhaps to allow easier reuse of modules or subsystems of code.

Third, packagesprovide namespaces in Java. 서로 다른 패키지 안에 있다면 클래스의 이름이 같아도 상관없다.

Typing java.util.ArrayList throughout code can begin to get tedious, and it clutters the code as well. Java provides a keyword import that allows identification of fully qualified class names and/or packages at the source file level. Use of import statements allows you to specify simple class names throughout the remainder of the source file.

The java.lang Package

The Java library contains classes so fundamental to Java programming that they are needed in many, if not all, classes. The classes String and Object are two such classes. The ubiquitous nature of these classes is such that the designers of Java wanted to save you from the nuisance of having to specify an import statement for them everywhere.

Lesson 1. Getting Started

Lesson 1. Getting Started

1장에서 배울 것은 :

  • 간단한 Java class 만들기
  • Java class를 가지고 노는 test class 만들기
  • JUnit famework 사용하기
  • 생성자에 대해 배우기
  • 위에서 작성한 code 리팩토링하기.


Testing

Test-driven development means that you will write tests for virtually every bit of code. It also means that you will write the tests first. The tests are a means of specifying what the code needs to do. After writing the corresponding code, the tests are run to ensure that the code does what the tests specify.

The production classes you build should know nothing about the tests written for them.

Design

You start by building only high-level designs, not highly detailed specifications. You will continually refine the design as you understand more about the customer needs. You will also update the design as you discover what works well and what doesn’t work well in the Java code that you build. The power of object-oriented development can allow you this flexibility, the ability to quickly adapt your design to changing conditions.

A Simple Test

You must designate the class as public in order for the testing framework JUnit to recognize it.

The classpath is a list of locations separated by semicolons under Windows or colons under Unix. You supply the classpath to both the compiler and the Java VM. A location can be either a JAR file (which contains compiled class files by definition) or a directory that contains compiled class files.

ex) javac -classpath c:\junit3.8.1\junit.jar StudentTest.java(the abbreviated keyword -cp.)

JUnit

Not only does the Java compiler need to know where the JUnit classes are, but the Java VM also needs to be able to find these classes at runtime so it can load them up as needed.

java -cp .;c:\junit3.8.1\junit.jar junit.awtui.TestRunner StudentTest


Adding a Test

public class StudentTest extends junit.framework.TestCase {
public void testCreate() {
}
}
  • the method must be declared public,

  • the method must return void (nothing),

  • the name of the method must start with the word test, in lowercase letters, and

  • the method cannot take any arguments ().

Creating a Student

new Student(“Jane Doe”);

You terminate each statement with a semicolon (;).

You place the new keyword before the name of the class to instantiate.

String literals represent object instances of the predefined Java class java.lang.String.

When the Java VM executes the new operator in this statement, it allocates an area in memory to store a representation of the Student object. The VM uses information in the Student class definition to determine just how much memory to allocate.

Creating the Student Class

class Student {}

Constructors

A constructor looks a lot like a method. It can contain any number of statements and can take any number of arguments like a method. However, you must always name a constructor the same as the class in which it is defined. Also, you never provide a return value for a constructor, not even void.

Local Variables

Student student = new Student(“Jane Doe”);

When the Java VM executes this statement, it executes the code to the right-hand side of the assignment operator (=) first, creating a Student object in memory. The VM takes note of the actual memory address where it places the new Student object. Subsequently, the VM assigns this address to a reference on the left-hand side, or first half, of the statement.

Returning a Value from a Method

String studentName = student.getName();

you are sending a message to the Student object, using the student reference assigned to in the previous statement.

String getName() { }

This getName method specifies instead a return type of String.

return “”;

The return statement here returns an empty String objecta String with nothing in it.

Refactoring

The first step is to eliminate the unnecessary local variables.
The second step: It is considered poor programming practice to embed String literals throughout your code. One reason is that the code can be difficult to follow if it is not clear what each String literal represents.

this

There are two ways to ensure that the value of the formal parameter is assigned to the field:
The first approach means you must rename either the parameter or the field.
The second approach for disambiguating the two is to use the same name for both, but where necessary refer to the field by prefixing it with the Java keyword this.