- 목표: 1단계가 되어보자(스스로 일일이 적어볼 수 있는 정도...) 지금은 인터넷 쳐서 대충 뜨문뜨문 하는거다..
-
Declaring variables in
static
keyword will lead it to be stacked in the memory without the necessity of declaring class. It works as global state. -
Member variables in class level scope, they must be declared within the class and are available for being directly accessed within the class.
- Member variables can be accessed outside a class (but it needs to be initialize new class though) with the following rules.
Modifier Package Subclass World public Yes Yes Yes protected Yes Yes No Default (no modifier) Yes No No private No No No
-
Variables declared inside a method have method level scope and can’t be accessed outside the method. Local variables don’t exist after method’s execution is over.
-
We have
this
keyword in Java to declare instance object of the class.
- As mentioned above, we have modifiers to determine the range of publicizing the classes.
- Object-Oriented Programming refers to using objects in programming.
- Polymorphism: Overloading & Overriding methods with the taking same name yet the program execute successfully.
public class Sum {
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
}
-
Inheritance: In Java, one class is allowed to inherit the features - including methods and fields - of another class.
- Super Class - The class whose features are INHERITED.
- Sub Class - The class that INHERITS the other classes with adding very own methods and fields.
- Reusability.
class derived-class extends base-class { //methods and fields }
-
Encapsulation: The feature means wrapping up of data and code under a single unit, not to disclose the raw data to the outside of the unit or class.
-
Abstraction: Achieved by Interfaces and abstract classes in order for classifying the objects.
- Instance method: They are the methods which require an object of its classes to be created before the class object itself can be called after creating the object of the class.
- Class: Class itself is a user defined blueprint from which objects are created. Object however, represents the real-life entities by holding the properties including state, behaviour and identity.
- You can initalize the state of objects by declaring the instance/object within the constructor of classes primarily, and create the object of class using
new()
keyword.
- Look very into the code directly as much I understand it.
class Bicycle {
public int gear;
public int speed;
public Bicycle(int gear, int speed){
this.gear = gear;
this.speed = speed;
}
public void applyBrake(int decrement){
speed -= decrement;
}
public void speedUp(int increment){
speed += decrement;
}
public String toString(){
return (gear + " " + speed);
}
}
class MountainBike extends Bicycle
{
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int gear, int speed, int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}
// the MountainBike subclass adds one more method
public void setHeight(int newValue)
{
seatHeight = newValue;
}
// overriding toString() method of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+
"\nseat height is "+seatHeight);
}
}
// driver class
public class Test
{
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
//No of gears are 3
//speed of bicycle is 100
//seat height is 25
// An example abstract class in Java
abstract class Shape {
int color;
abstract void draw();
}
abstract class Base {
Base() {
System.out.println("Base Constructor Called");
}
abstract void fun();
}
class Derived extends Base {
Derived() {
System.out.println("Derived Constructor Called");
}
void fun() {
System.out.println("Derived fun() called");
}
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
d.fun();
}
}
//Base Constructor Called
//Derived Constructor Called
//Derived fun() called
- Interfaces specify what a class must do and not how. It is the blueprint of the class. It only enumerates the sets of methods that NEEDS TO BE APPLIED BY INHERITING CLASSES.
추상 클래스는 그 추상 클래스를 상속받아서 기능을 이용하고, 확장시키는 데 있습니다. 반면에 인터페이스는 함수의 껍데기만 있는데, 그 이유는 그 함수의 구현을 강제하기 위해서 입니다. 구현을 강제함으로써 구현 객체의 같은 동작을 보장할 수 있습니다. (...) 이렇게 추상 클래스와 인터페이스를 나누는 이유는 자바가 다중 상속을 금지하기 때문입니다. 다중 상속을 허용할 경우 어떤 부모 클래스에서 같은 이름의 메소드가 호출될 지 판단하기 어렵기 때문입니다.
import java.io.*;
interface In1
{
// public, static and final
final int a = 10;
// public and abstract method that needs to be constructed
void display();
}
// A class that implements the interface.
class TestClass implements In1
{
// Implementing the capabilities of interface.
public void display()
{
System.out.println("Geek");
}
// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
- Method overloading is Compile time polymorphism. In method overloading, more than one methods shares the same method name with different signatures within the class.
- Take the example in the part of OOP.
- Method overriding is a Runtime polymorphism. The derived class attempts to override the specific methods that are already provided by the basic/parent class. However, in method overriding, return type must be the same as the derived method as compared to method overriding.
- Take the example in the part of Inheritance.
-
Best links to be referred: https://github.com/jojoldu/blog-code/tree/master/enum-settler
-
Enumeration, or enum serves as representative of a group of named constraints.
-
클래스처럼 보이게 하는 상수; 서로 관련 있는 상수들을 모아 심볼릭한 명칭의 집합으로 정의한 것.
enum Color
{
RED, GREEN, BLUE;
}
public class Test
{
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1); //RED
}
}
import java.util.Scanner;
// An Enum class
enum CodesquadMasters
{
HONUX, JK, YAGOM, CRONG;
}
public class CodeSquadMasters
{
CodeSquadMasters codesquadmasters;
// Constructor
public CodeSquadMasters(CodesquadMasters codesquadmasters)
{
this.codesquadmasters = codesquadmasters;
}
// Prints a line about Masters using switch
public void whoisOurMaster()
{
switch (codesquadmasters)
{
case HONUX:
System.out.println("HONUX TEACHES JAVA BACKEND.");
break;
case JK:
System.out.println("JK TEACHES MOBILE IOS.");
break;
case CRONG:
System.out.println("CRONG TEACHES JAVASCRIPT FRONTEND");
break;
case YAGOM:
System.out.println("YAGOM TEACHES MOBILE IOS.");
break;
default:
System.out.println("THEY ARE NOT OUR MASTERS.");
break;
}
}
public static void main(String[] args)
{
String str = "HONUX";
CodeSquadMasters codesquadmasters2020 =
new CodeSquadMasters(codesquadmasters2020.valueOf(str));
codesquadmasters2020.whoisOurMaster(); //HONUX TEACHES JAVA BACKEND.
}
}
- Error: An Error indicates serious problem that a reasonable application should not try to catch.
- Exception: Exception indicates conditions that a reasonable application might try to catch.
- Consistent API : The API has a basic set of interfaces like Collection, Set, List, or Map. All classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have some common set of methods.
Collection Map
/ / \ \ |
/ / \ \ |
Set List Queue Dequeue SortedMap
/
/
SortedSet
[Core Interfaces in Collections]
Note that this diagram only shows core interfaces by GeeksforGeeks.
- Set, List(LinkedList, ArrayList), Queue, Deque, Map(HashMap, SortMap)
- Nested Class(static): Define a class within a class to use as static variables.
- The scope of a nested class is bounded by the scope of its enclosing class. Thus in above example, class NestedClass does not exist independently of class OuterClass.
- A nested class has access to the members, including private members, of the class in which it is nested. However, reverse is not true i.e. the enclosing class does not have access to the members of the nested class.
class OuterClass
{
...
class NestedClass
{
...
}
}
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
// static nested class
static class StaticNestedClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can access display private static member of outer class
System.out.println("outer_private = " + outer_private);
// The following statement will give compilation error
// as static nested class cannot directly access non-static membera
// System.out.println("outer_y = " + outer_y);
}
}
}
// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();
}
}
- Inner class(non-static): Define a class within a class to use as instance variables.
// Java program to demonstrate accessing
// a inner class
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;
// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer class
System.out.println("outer_y = " + outer_y);
// can also access private member of outer class
System.out.println("outer_private = " + outer_private);
}
}
}
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display();
}
}
- Static nested classes do not directly have access to other members(non-static variables and methods) of the enclosing class because as it is static, it must access the non-static members of its enclosing class through an object. That is, it cannot refer to non-static members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.
- Non-static nested classes (inner classes) has access to all members(static and non-static variables and methods, including private) of its outer class and may refer to them directly in the same way that other non-static members of the outer class do.
- A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
- Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
- Intermediate Operations: Map, Filter, sorted
- Terminal Operations: collect, forEach, reduce
List<String> list = List.of("mad", "play");
Stream<String> stream = list.stream();
String[] arr = new String[]{"mad", "play"};
Stream<String> stream = Arrays.stream(arr);
// 0번 인덱스만 선택(closed range)
Stream<String> specificStream = Arrays.stream(arr, 0, 1);
// "mad" 출력
specificStream.forEach(System.out::println);
-
Stream aims to exploit the functional interface - lambda expression. In the past, it would be imperative for developers to pop the elements from the collections by iterating all of orders. However, with using lambdas and stream, you are able to reduce the amount of codes and succinctly.
-
With using stream, it is possible to conduct the task by chunking the stream elements - we called it parallel stream.
-
Examples of parallel stream that returns the sum of
1 to n
after receiving integern
as parameter.public static long sequentialSum(long n){ //Stream.iterate(initial value, next value) return Stream.iterate(1, i -> i + 1) // 무한 자연수 스트림 생성 .limit(n) //n개 이하로 제한 .reduce(0, Long::sum) // 모든 숫자를 더 하는 스트림 리듀싱 연산 }
public static long parallelSum(long n) { return Stream.iterate(1, i -> i + 1) .limit(n) .parallel() // 스트림을 병렬 스트림으로 변환 .reduce(0, Long::sum); }
-
The stark difference between two codes is streams are chunked in many ways.
-
Combining two results of partial sum into reducing calculations so that the overall results can be elicited.
-
(...) it was not to be a general purpose Maybe type, as much as many people would have liked us to do so. Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent “no result”. - Brian Goetz.
API Note: Optional is primarily intended for use as a method return type where there is a clear need to represent “no result,” and where using null is likely to cause errors. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.
- If the code is vulnerable to process the
NULL
result, in the runtime execution, Developers might find unexpected NPE(NULLPointer Exception).
/* 주문 */
public class Order {
private Long id;
private Date date;
private Member member;
// getters & setters
}
/* 회원 */
public class Member {
private Long id;
private String name;
private Address address;
// getters & setters
}
/* 주소 */
public class Address {
private String street;
private String city;
private String zipcode;
// getters & setters
}
//Order 클래스는 Member 타입의 member 필드를 가지며, Member 클래스는 Address 타입의 address 필드를 갖는다.
- We assume there is a method for the purpose of checking the city that customers reside.
public String getCityOfMemberFromOrder(Order order) {
return order.getMember().getAddress().getCity();
}
- NPE could be happened if
null
parameter passes to order class - order.getMember() could benull
, and as slippery slope the consequence continues.
String city = getCityOfMemberFromOrder(order); // returns null
System.out.println(city.length()); // throws NPE!
- It could be pale in comparison to comparing
null
exception using if-else condition, doesn't it?
public String getCityOfMemberFromOrder(Order order) {
if (order != null) {
Member member = order.getMember();
if (member != null) {
Address address = member.getAddress();
if (address != null) {
String city = address.getCity();
if (city != null) {
return city;
}
}
}
}
return "Seoul"; // default
}
- The plethora of well-known functional programming languages solve this problem by setting the value as the value which the developer does not know whether it is NULL or validate output...
- Java was inspired from them.
Optional<Order> maybeOrder; // Order 타입의 객체를 감쌀 수 있는 Optional 타입의 변수
Optional<Member> optMember; // Member 타입의 객체를 감쌀 수 있는 Optional 타입의 변수
Optional<Address> address; // Address 타입의 객체를 감쌀 수 있는 Optional 타입의 변수
- Some methods of Optional...
- get() : 비어있는 Optional 객체에 대해 NoSuchElementException을 던진다.
- Do not understand much without coding from the bottom.. get to study when using optional.
- 데이터를 외부에서 읽고, 외부에서 출력하는 작업: Input, Output
- Java I/O - 스트림을 통해서 입력&출력
- 단방향으로 연속적이게 흘러가는 형태: 출발지에서 나와 도착지로 들어감
- 프로그램이 네트워크 상의 다른 프로그램과 데이터 교환을 위해 두 스트림이 모두 필요함.
- 출발지: OutputStream
- 도착지: InputStream
- 단방향으로 연속적이게 흘러가는 형태: 출발지에서 나와 도착지로 들어감
- Java.io 패키지 내 API 제공 : 다양한 I/O 클래스 제공
- 입출력 스트림 대상에 따라 세분화 : 파일, 콘솔, 네트워크 상 프로그램
- 데이터 타입(단위)에 따라 세분화 : Byte, Char
- 바이트 기반 스트림 : 이미지, 멀티미디어, 문자 등 모든 종류의 데이터(XXXInputStream - XXXOutputStream)
- 문자 기반 스트림 : 문자만 주고 받을 수 있도록 특화됨(XXXReader - XXXWriter)
Swift의 Lena는 이렇게 설명했어
메소드와 함수의 차이: https://www.notion.so/d9a036e38b9044e9a130858ed356ae0b
Class, Instance, Object 설명과 관계 https://www.notion.so/Instance-Object-Class-ef08bcec969d424e98d6cb29a4572289