JAVA | Class

Yunny.Log ·2022년 10월 20일
0

JAVA

목록 보기
27/29
post-thumbnail

range of method and variable of class

  • User defined class
    • Main class : A class whose name is the same as the file name
    • Sub-class : Classes other than the main class
  • A method definition must occur inside a class (anywhere).
  • main method inside the main class is executed first

< Class method >

(1)

  • 인스턴스 변수
  • 메소드

(2)

method

Method parameter **

(+) parameter(매개변수)
다음 cancat 함수 정의에서 str1과 str2는 parameter .

def cancat(str1, str2):
  return a +" "+ b

(+) argument(전달인자)
cancat 함수를 호출할 때, 입력값 “parameter”와 “argument”는 argument

cancat("parameter", "argument")
  • method 선언 시 끼워져있는 호출애들

When Method( 10, 20) is invoked, parameter 10, 20 : real parameter in definition part, parameter sijak, keut : dummy parameter

– Note that each of the formal parameters must be preceded by a type name, even if there is more than one parameter of the same type. Corresponding arguments must match the type of their corresponding formal parameter, although in some simple cases an automatic type cast might be performed by Java.
동일한 유형의 매개변수가 두 개 이상 있더라도 각 형식 매개변수 앞에는 유형 이름이 와야 합니다.
해당 인수는 해당 형식 매개변수의 유형과 일치해야 하지만 일부 간단한 경우에는 Java에서 자동 유형 캐스트를 수행할 수 있습니다.

– For example, if you plug in an argument of type int for a parameter of type double, then Java will automatically type cast the int value to a value of type double.
예를 들어, double 유형의 매개변수에 대해 int 유형의 인수를 연결하면 Java는 자동으로 int 값을 double 유형의 값으로 유형 캐스트합니다.

– The following list shows the type casts that Java will automatically perform for you.

byte -> short -> int -> long -> float ->double

Example of compile error

Variable and Array Parameters ****

When parameter is variable or array
매개변수가 변수 또는 배열인 경우

  • The influence of Changing dummy parameter is as follows.
    더미 파라미터 변경의 영향은 다음과 같습니다.
    • When real parameter is variable, changing the value of dummy variable has no effect
      실제 매개변수가 변수일 때 더미 변수의 값을 변경해도 효과가 없습니다.
    • When real parameter is array, changing the value of dummy array cheanges value of the real parameter
      실제 매개변수가 배열인 경우 더미 배열의 값을 변경하면 실제 매개변수의 값이 변경됩니다.
    • In array parameter case, if changing the value of dummy array doesn’t influence value of the real parameter, you must do arraycopy() into another array arraycopy() before method is invoked.
      배열 매개변수의 경우 더미 배열의 값을 변경하지 않으면
      실제 매개변수의 값에 영향을 미치려면 메서드가 호출되기 전에 arraycopy()를 다른 배열 arraycopy()에 수행해야 합니다.

  • a 배열은 바뀜, 그러나 b는 변하지 않음 **

    배열은 바뀌지만 변수는 안바뀌지

a[0] : 11 
a[1] : 13 
a[2] : 15 
a[3] : 17 
a[4] : 19 

b : 10

Method Overloading

  • Two or more methods in the same class can have the same method name.
    This is called overloading.
    동일한 클래스에 있는 둘 이상의 메소드는 동일한 메소드 이름을 가질 수 있습니다.

  • Overloading occurs if several methods have the same name but different
    parameters.
    여러 메소드가 이름은 같지만 매개변수 타입이나 갯수가 다른 경우 오버로딩이 발생

  • Multiple methods can be defined within the same class, and they can be
    called in the main class.

    • Overloading using different number of parameters by different number of method parameter
      다른 수의 메소드 매개변수에 의해 다른 수의 매개변수를 사용하여 오버로딩

    • Overloading using different type of parameters by different parameter type (data type)
      다른 매개변수 유형(데이터 유형)에 따라 다른 유형의 매개변수를 사용하여 오버로딩

Method Overloading by different number of parameter

Method Overloading by different parameter data type

Global and local variables

Static and Local Variables

(1) static :
declared within the class and outside the method can be accessed from anywhere within the subclass and main class ( = almost global variable )

(2) local :
declared within the method cannot be accessed outside the method
메서드 내에서 선언된 메서드는 메서드 외부에서 액세스할 수 없습니다.

Before Assignment

  • static 변수는 자동 값 존재, 그러나 지역 변수는 그딴 것 없어서, 암것도 할당 안해주면 에러남 ㅋ
int, float, double : 0
boolean : false
String : null
char : '\0' 

Object-Oriented Programming

Class object

className varName = new className(param1, param2, …);

– Class object varName is created by new operator.
– The className is the method and it is so called constructor.
– The constructor must have class name.
– The class field (class member) includes global variables

  • method in the class is invoked by
varName.methodName(...);

Constructor

  • You often want to initialize the instance variables for an object when you
    create the object.
    종종 객체의 인스턴스 변수를 초기화하고 싶을 때 개체를 만듭니다.

(ex) PanMae 클래스의 PanMae

  • A constructor is a special variety of method that is designed toperform such initialization
    생성자는 특별한 다양한 메소드입니다. 이러한 초기화를 수행하도록 설계됨

(ex) PanMae in PanMae class

Constructor 규칙

  • must have the same name as the class
  • doesn’t have return type.
    ex) public void PanMae(…) (X), public int PanMae(…) (X)
  • Overloading is possible
  • is called by new class

Class object construction and destruction

Since Java does automatic garbage collection, manual memory reclamation is not needed, and Java does not support destruction
Java는 자동 가비지 수집을 수행하므로 수동 메모리 회수
필요하지 않으며 Java는 파괴를 지원하지 않습니다.

PanMae pmae1 = new PanMae(“SaGwa”, 5, 1000);
  • Call constructor method PanMae( ) of PanMae class
    PanMae() 호출
    • construction of class object pmae1 in memory
      메모리에 클래스 객체 pmae1 생성
    • initialization of variable in class object pmae1
      클래스 객체 pmae1의 변수 초기화
    • When program is terminated, class object pmae1 is eliminated from
      프로그램이 종료되면 클래스 객체 pmae1이 다음에서 제거

Field

  • Global variable in Class is called field or member
  • 클래스의 전역 변수를 필드 또는 멤버라고 합니다.
    ex) pmyung,sryang,danga

Execution of Class object method

Pmae1.PyoSi( ); 

execution of PyoSi() in PanMae class

Class type variable value and class object

  • 생성자로 생성 안하면 당연히~ null 값 가지지

public and private modifiers

  • private : 인스턴스 변수는 클래스 밖에서는 접근이 되지 않음

SaGwa	5	1000

pmae.pmyung : SaGwa
pmae.sryang : 5

Static field

(+) 공유 개념을 들 수 있다. static 으로 설정하면 같은 곳의 메모리 주소만을 바라보기 때문에 static 변수의 값을 공유

(+) static 키워드 앞에 final이라는 키워드를 붙이면 된다. final 키워드는 한번 설정되면 그 값을 변경할수 없다. 변경하려고 하면 오류가 발생한다.

method

Method

  • static method
    static method must use only static variable(object)
    • Method are methods that do not operate on objects.
    • For example, the pow method of the Math class is a static method.
    • The expression: Math.pow(x,y)
  • public method
    • it is used outside the other class operation.
    • default is public
    • ex) public PanMae(..) is equal PanMae()
  • private method
    • it is never used outside the other class operations.
    • Some of these internal methods may not particularly useful to the public.
    • Such methods are best implemented as private

(+)

this parameter

  • 메서드 정의 정의 내에서 키워드 'this'를 호출 개체의 이름으로 사용할 수 있습니다.
  • 호출 객체 없이 클래스의 인스턴스 변수 또는 다른 메서드를 사용하는 경우 'this'는 호출 객체로 이해됩니다.
  • This denotes the implicit parameter, that is, the object that is being constructed
    이것은 암시적 매개변수, 즉 생성 중인 객체를 나타냅니다.
Public Employee(String name, double salary){ 
  this.name = name;
  this.salary = salary; 
}

(+) this . this ()

▪ this : 인스턴스 자신을 가리키는 참조 변수로 인스턴스의 주소가 저장되어 있다.
▪ this(), this(….) : 클래스 생성자에서 같은 클래스 내의 다른 생성자를 호출할 때 사용
한다. 이 때에는 반드시 첫 줄에서 사용되어야 한다

(1) this - 자기 자신 가리키는 용도

(2) this() - 생성자


This

format : this(param1, param2, …);
– The constructor calls another constructor of the same class.
같은 클래스에서 다른 생성자 호출할거야!!
– Call Only in constructor method (constructor)

– Be execute constructor method with same parameter type and number of parameter
매개변수 유형과 매개변수 개수가 동일한 생성자 메서드를 실행해야 합니다.

Array object

  • class object as an array


SaGwa	5	1000
Bae 	3	2000
PoDo 	7	500

(+) Array of Objects 객체 배열
참조 자료형으로 선언하는 배열로, 같은 참조 자료형의 객체만 저장된 배열
기본적인 사용 방법은 배열과 동일함

Inheritance

  • keyword extends :

    • indicate that you are making a new class(derived class or subclass) that derives from an existing class(base class or super class).
      새로운 클래스(파생 클래스 또는 하위 클래스)를 만들고 있음을 나타냅니다.
      기존 클래스(기본 클래스 또는 수퍼 클래스)에서 파생됩니다.
  • Keyword super : is for use in a subclass, indicate base class.

    • 부모 클래스 생성자 호출할 때 사용
      super(param1, param2, …);
    • execute constructor method with same parameter and type in base class.
    • 기본 클래스에서 동일한 매개변수 및 유형으로 생성자 메소드를 실행합니다.

(+) this 와 super

Protected field

  • only usable for declared class and subclass

Assigning the subclass to the super (base) class

PanMae pmae = new SalePanMae(Lemon, 7, 3000, 0.22)

– Super class variable, array can have subclass object as value.
– In previous program, PanMae and SalePanMae are all jumbled together onPanMae object. In this case, datas aren’t processed well.
– It is solved by assigning subclass to super(base) class.
– 상위 클래스 변수, 배열은 하위 클래스 객체를 값으로 가질 수 있습니다.
– 이전 프로그램에서 PanMae와 SalePanMae는 모두 PanMae 개체에서 함께 뒤죽박죽
– 상위(기본) 클래스에 하위 클래스를 할당하여 해결합니다.


(+)

Class Type Conversion

  • If you want to use subclass method in super class, you must use casting operation.

instanceof operator

package

– A package is Java’s way of forming a library of classes.
– Package are convenient for organizing tour work and for separating your
work form code libraries provided by others
– is a collection of classes
– User-defined library, package is same #include ”… .h” in C/C++
– The name of Package file(pkgClass.java) must be same the name of
package class name
– pkgClass.java file must be directory of Package name
– 패키지는 클래스 라이브러리를 구성하는 Java의 방법입니다.
– '패키지'는 작업을 정리하는 데 편리합니다.

  • '패키지'는 분리에 편리합니다.
    다른 사람이 제공한 작업 양식 코드 라이브러리
    – 클래스 모음입니다.
    – 사용자 정의 라이브러리, 패키지는 C/C++에서 #include ”… .h”와 동일
    – 패키지 파일(pkgClass.java)의 이름은 파일의 이름과 같아야 합니다.
    패키지 클래스 이름
    – pkgClass.java 파일은 패키지 이름의 디렉토리여야 합니다.

– For example, suppose the following is a directory listed in tour
CLASSPATH variable
c:\libraries
And suppose your package classes are in the directory
:\libraries\news\pkg
In this case, the package should be named
news.pkg
and all the classes in the file must start with the package statement
package news.pkg


(+)

(+) 다른 패키지에 있는 클래스 사용하기


import

  • import (using packages)
    • 프로그램 또는 클래스 정의를 포함하는 파일의 시작 부분에 패키지 및 클래스의 이름을 지정하는 import 문을 배치하여 모든 프로그램 또는 클래스 정의에서 패키지의 클래스를 사용할 수 있습니다. – Syntax:
      import Package_name.Class_Name;
      – Examples
      import pkg.pkgClass;
      import pkg.*;
      You can import all the classes in a package by using an asterisk in place of the class’s name

interface

  • Class Interface
    When executing method existed in other class, you can use interface method.
  • Interface type has compatibility with corresponding implements class.
    인터페이스 유형은 해당 구현 클래스와 호환됩니다.
    • Above example, IntFace x = new PanMae( ) ;
    • intFace type has compatibility with corresponding implement class PanMae
      class
    • When intf is IntFace type interface and pm is PanMae type,
      - intf = pm ;
      //assignment is possible

Interface method parameter

  • When Interface1 method is executed,
    • IntFace x = new PanMae; in ClassAMethod( ) doesn’t execute interface method from construction of interface type object. But it is executed by transmitting corresponding object to method.
    • IntFace x = 새로운 PanMae;
  • ClassAMethod()에서 인터페이스 유형 객체의 생성에서 인터페이스 메소드를 실행하지 않습니다. 단, 해당 객체를 메소드로 전송하여 실행합니다.
    Modification of this code is next page example
    – In PanMae and ClassA class, constructor method is not declared.
    But PanMae pm = new PanMae( ); and ClassA ca = new ClassA( ); is normally Compiled/executed.
    Because all class is derived from object class and constructor offered by object class is executed when classname() constructor in class is not declared.
    PanMae 및 ClassA 클래스에서는 생성자 메서드가 선언되지 않습니다.
    하지만 PanMae pm = new PanMae( ); 및 ClassA ca = new ClassA( ); 일반적으로 컴파일/실행됩니다.
    모든 클래스는 객체 클래스에서 파생되고 객체 클래스에서 제공하는 생성자는 클래스의 classname() 생성자가 선언되지 않은 경우 실행되기 때문입니다.

Object class

Principal CLASS
– Object class

`package java.lang;`

/ The root of the Class hierarchy. Every Class in the system has Object as its
ultimate parent. Every variable and method defined here is available in
every Object.
/

public class Object {
public final native Class getClass();

/ Returns the Class of this Object. Java has a runtime representation for
classes- a descriptor of type Class- which the method getClass() returns for
any Object.
/

public native int hashCode();

/ Returns a hashcode for this Object. Each Object in the Java system has a
hashcode. The hashcode is a number that is usually different for different
Objects. It is used when storing Objects in hashtables. Note: hashcodes can
be negative as well as positive.
/

public boolean equals(Object obj)
	{
	return (this == obj);
	}

/ Compares two Objects for equality. Returns a boolean that indicates
whether this Object is equivalent to the specified Object. This method is
used when an Object is stored in a hashtable. @return true if these Objects
are equal; false otherwise.
/

Character class - 다양 메소드들

– boolean isLowerCase(char ch);
returns true if ch represents a lower-case letter; otherwise it returns false.
– boolean isUpperCase(char ch);
returns true if ch represents a capital letter; otherwise it returns false.
– char toLowerCase(char ch);
returns the lower-case equivalent of ch if one exists; otherwise it returns ch.
– char toUpperCase(char ch);
returns the upper-case equivalent of ch if one exists; otherwise it returns ch.
– boolean isWhitespace(char ch);
returns true if ch represents a white-space character. otherwise it returns false.

Integer class

Integer Class

  • static String toString(int n, int radix)
    	```java
    String s = Integer.toString(“63”, 16); // s <= “3F”
  • static int parseInt(String s)
int n = Integer.parseInt(123); // n <= 123
  • Static Integer valueOf(String s)

    • returns an Integer object holding the value of the specified String.
  • The argument is interpreted as representing a signed decimal integer. The result is an Integer object that represents the integer value specified by the string.

  • int intValue( )

    • returns the value of this Integer as an int
  • long longValue( )

    • returns the value of this Integer as a long.

Integer, long, float, double type object

– Integer(int I)
– Long(long l)
– Float(float f)
– Double(double d)

  • constructs a newly allocated integer/long/float/double object that represents the specified int/long/float/double value.
    – ex) Integer in = new Integer(10);

Math class

  • static final double PI = 3.14159;
  • static double random( )
    • returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
  • double d = Math.cos(30);
    returns the trigonometric cosine of an angle radian 30
  • static double sqrt(double x) // root function
  • static double exp(double x) // exponential function
  • static double log(double x) // log function
  • static int round(double x) // round x
  • static int abs(int x) // returns the absolute value of an int value.
  • static int max(int x, int y) // returns the greater of two int values.
  • static int min(int x, int y) // returns the smaller of two int values.
  • double pow(double x, double y)
    // returns the value of the first argument raised to the power of the second
    argument x.

0개의 댓글