Java 정리 4

2021. 1. 19. 17:11·JAVA
728x90
반응형

 

Properties and actions

Classes and instances are two important object-oriented programming concepts.

In fact, "instance" is another name for an object and a "class" is a blueprint of an instance

An instance has a properties and actions and we define them in a class.

 

Creating instances

we create an instance from a class as follow : new ClassName( );

ex )

class Main {
    public static void main(String[] args) {
       new Person(); //create an instance of the Person class
    }
 
}
Colored by Color Scripter
cs

 

Assigning instances to variables

To use an instances, we assign it to a variable as follows :

ClassType variableName = new ClassName( )

we specify the class type in front of the instance instead.

ex )

class Main {
    public static void main(String[] args) {
       Person person1 = new Person(); 
    }
 
}
 
Colored by Color Scripter
cs

 

Instance fields and instance methods

we call the properties of the instance as instance fields and actions of the instance as instance methods.

 

Defining methods : public returnType methodName( )

instance method has no static

ex )

class Person {
    public void hello() {
        System.out.println("Hello !");
    }
}
Colored by Color Scripter
cs

 

Calling instance method

The syntax to call an instance method is as follows:

instanceName.methodName( );

ex )

Person person1 = new Person ( );

Person person2 = new Person ( );

person1.hello( );

person2.hello( );

 

Declaring instance fields

we declare these variable at the very top of the class body

: public dataType variableName

ex) public String name;

 

We use " . " to access the instance field as follows : instanceName.feildName( )

ex )

Person person1 = new Person( );

person1.name = "Chris";

 

System.out.println( person1.name );   -> "Chris"

 

This

To access an instance field inside a method, we use a special variable called this. You can only use "this" inside the method of your class. When an instance calls the method, this is replaced by the instance.

ex )

class Main {
    public static void main(String[] args) {
       Person person1 = new Person();
       person1.name = "chris";
       person.hello();
 
    }
 
}
 
class Person {
    public String name;
 
    public void hello() {
        System.out.println( "Hello!" + this.name );
    }
}
Colored by Color Scripter
cs

 

Constructors : a class has a construcor

A constructor is a special method that is called automatically when we create an instance using "new".

Constructor has its own definition

1. the constructor name must be the same as the class name

2. do not write return or void

ex )

class Main {
    public static void main(String[] args) {
       Person person1 = new Person();
 
    }
 
}
 
class Person {
    public String name;
 
    Person() {
        System.out.println("Created a new instance");
                    //Runs right after an instance is made
    }
}
Colored by Color Scripter
cs

 

Passing information to the constructor

when we create an instance using "new", we can pass arguments to the ( ) of new ClassName( )

setting field using the constructor

ex )

class Main {
    public static void main(String[] args) {
       Person person1 = new Person("Chris");
 
       System.out.println( person1.name );
 
    }
 
}
 
class Person {
    public String name;
 
    Person( String name ) {
        this.name = name;
    }
}
Colored by Color Scripter
cs

 

Declaring class fields

Class fields which belong to a class : public static dataType variableName

 

Accessing class fields

We can access a class field as follows : ClassName.ClassFieldName

ex )

class Main {
    public static void main(String[] args) {
       System.out.println("Total: " + Person.count + " people.");
       Person person1 = new Person( ... );
       Person person2 = new Person( ... );
       System.out.println("Total: " + Person.count + " people.");
 
    }
 
}
 
class Person {
    public static int count = 0;
        ...
    Person( String firstName ... ) {
        Person.count++;
    }
}
 
//Total : 0 people.
//Total : 2 people.
Colored by Color Scripter
cs

 

Methods that belong to a class

we define class methods like so : public static returnType methodName( )

To call a class method : ClassName.methodName( )

 

Overloading contructors

overloading allows you to define methods with the same name if they have an unique list of arguments.

ex )

Person person1 = new Person( "Kate", "Jones", ... );   (5 arguments)

-> Person ( String name, String lastName ... )

 

Person person2 = new Person( "John", "Christopher", "Smith", ... );    (6 arguments)  

-> Person ( String name, String middleName, String lastName ... )

 

Defining contructors with different parameters ( overloading )

 

Calling other contructors

we can use this( ) to call one constructor from another.

You can pass arguments between the ( ) of this( )

we can only call this( ) at the beginning of the constructor

 

null is a special value that means 'nothing'

If we don't assign an initial calue to a variable or a field when declaring it Java assigns it a fixed dafault value.

String - null        double - 0.0

int - 0        boolean - false

 

Encapsulation : hiding information of the class that is unneeded by the user.

we can use public to allow access from outside the class and use private to prevent access.

 

Access from outside the class

It is possible to access it from within the class even if it's private. On the other hand, it is possible to access it from within the class even if it's private.

 

Getter : getFieldName( );

Once we make a field private, in order to get the field value safely from outside the class, we have to define an instance method that only returns the value of the field.

ex )

class Main {
    public static void main(String[] args) {
       Person person1 = new Person;
 
       System.out.println( person1.getMiddleName() );
       // print "Terry"
 
    }
 
}
 
class Person {
    ...
    private String middleName = "Terry";
    ...
    public String getMiddleName() {
        return this.middleName;
    }           //return the field values
}
Colored by Color Scripter
cs

 

Updating field value

If you set the permission of a field to private, you can no longer update the value of the field from outside the class.

 

Setter : setFieldName( );

we need to define an instance method to change the value of the field. Such an instance method is called a setter.

ex )

class Main {
    public static void main(String[] args) {
       Person person1 = new Person;
 
        person1.setMiddleName( "Terry" );
        System.out.println( person1.getMiddleName() );
 
        //print "Terry"
    }
 
}
 
class Person {
    ...
    private String middleName = "Terry";
    ...
    public void setMiddleName( String middleName ) {
        this.middleName = middleName;
    }           //set the field values
}
 
Colored by Color Scripter
cs

 

Encapsulation standard

Fields ... private

Methods ... public

 

 

출처 : progate.com/dashboard

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'JAVA' 카테고리의 다른 글

Java 정리 3  (0) 2021.01.18
JAVA 정리 2  (0) 2021.01.15
Java 정리 1  (0) 2021.01.14
'JAVA' 카테고리의 다른 글
  • Java 정리 3
  • JAVA 정리 2
  • Java 정리 1
waVwe
waVwe
    반응형
  • waVwe
    waVwe 개발 블로그
    waVwe
  • 전체
    오늘
    어제
    • ALL (184)
      • Python (1)
      • Spring (15)
      • DevOps (10)
      • Git (6)
      • JAVA (4)
      • C (22)
      • 코테 문제 풀이 (124)
        • 프로그래머스 (43)
        • 백준 (2)
        • 정올 (64)
        • SW Expert Academy (1)
        • 온코더 oncoder (14)
  • 블로그 메뉴

    • 홈
    • 방명록
  • 링크

    • 🐙 Github
  • 공지사항

  • 인기 글

  • 태그

    devops
    C언어
    아파치카프카
    이진트리
    깃
    프로그래머스
    자료구조
    도커
    progate
    온코더
    docker
    Til
    스프링부트
    코테
    연결리스트
    깃헙
    스프링
    스파르타코딩
    내일배움캠프
    springboot
    while문
    알고리즘
    스파르타코딩클럽
    MSA
    C
    정올
    java
    형변환
    CI/CD
    자바
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
waVwe
Java 정리 4
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.