= Object-Oriented Programming(객체 지향 프로그래밍)
즉, 클래스는 객체에 대한 템플릿이고,
객체는 클래스의 인스턴스
개별 객체가 생성되면 해당 객체는 클래스의 모든 변수와 메서드를 상속
자바의 모든 것은 클래스와 객체, 그리고 그 속성과 메서드와 연관
클래스는 객체 생성자이거나 객체를 만드는 "청사진"
Main 클래스를 만들고 변수 x 지정
Main.javapublic class Main {
int x = 5;
}
클래스는 항상 첫 글자를 대문자로 시작
자바 파일 이름은 항상 클래스 이름과 일치
myObj 객체를 생성하고 x의 값을 출력public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
// 5
하나의 클래스에 여러 객체 생성 가능
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
// 5
// 5
클래스의 객체를 생성하여 다른 클래스에서 접근하는 경우
Main.java
public class Main {
int x = 5;
}
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
// 5
이전 예시에서의 x는 클래스의 속성 또는 클래스 내의 변수
Main 클래스에 x, y 두 가지 속성 지정
public class Main {
int x = 5;
int y = 3;
}
.을 사용하여 속성에 접근 가능-MyObj.x로 속성에 접근
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
// 5
public class Main {
int x;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}
}
// 40
public class Main {
int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}
}
// 25
final을 이용하여 속성 정의public class Main {
final int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
myObj2.x = 25;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
// 5
// 25
public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
// Name: John Doe
// Age: 24
public class Main {
static void myMethod() {
System.out.println("Hello World!");
}
public static void main(String[] args) {
myMethod();
}
}
// "Hello World!"
static
public
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
// Create a Main class
public class Main {
// Create a fullThrottle() method
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}
// Create a speed() method and add a parameter
public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}
// Inside main, call the methods on the myCar object
public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}
// The car is going as fast as it can!
// Max speed is: 200
클래스의 객체를 생성하고 다른 클래스에서 해당 객체에 접근하는 것 권장
Main.java
public class Main {
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}
public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}
}
Second.javaclass Second {
public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}
// The car is going as fast as it can!
// Max speed is: 200
void 같은 반환 타입 불가/ Create a Main class
public class Main {
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
// 5
public class Main {
int x;
public Main(int y) {
x = y;
}
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}
// 5
public class Main {
int modelYear;
String modelName;
public Main(int year, String name) {
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Main myCar = new Main(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
// 1969 Mustang
public class Main
우리가 자주 보는 이 public이 수정자, 제어자
클래스, 속성, 메서드 및 생성자에 대한 접근 수준을 설정하는 데 사용
1. Class의 경우
: 모든 클래스에서 접근 가능
public: 같은 패키지 내의 클래스에서만 접근 가능
default
따로 설정하지 않을 시 적용되는 기본 접근 제어자
2. attributes, methods and constructors의 경우
: 모든 클래스에서 접근 가능
public: 같은 패키지 내의 클래스에서만 접근 가능
default: 같은 패키지 내의 클래스 또는 해당 클래스를 상속받은 클래스만 접근 가능
protected: 선언된 클래스 내에서만 접근 가능
private
1. Class의 경우
: 다른 클래스에 상속 불가
final: 추상화된 클래스로 객체 생성 불가
abstract
→ 이를 상속받은 하위 클래스에서 가능
2. attributes, methods의 경우
: 재정의 및 수정 불가
final: 특정 객체가 소속되어있는 것이 아니라 클래스 자체에 소속
static: 추상화된 클래스에서만 사용 가능
abstract(only for methods)abstract void run();메소드의 본문이 존재하지 않고, 위와 같이 선언되며
실제 구현은 이를 상속받은 하위 클래스에서 가능
: 객체 직렬화 시 제외
transient: 한 번에 하나의 스레드만 접근 가능
synchronized: 스레드의 로컬 캐시에 저장되지 않고, 항상 메인 메모리에서 값을 직접 조회
volatile
public class Main {
final int x = 10;
final double PI = 3.14;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final variable
myObj.PI = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method
}
}
// Code from filename: Main.java
// abstract class
abstract class Main {
public String fname = "John";
public int age = 24;
public abstract void study(); // abstract method
}
// Subclass (inherit from Main)
class Student extends Main {
public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
System.out.println("Studying all day long");
}
}
// End code from filename: Main.java
// Code from filename: Second.java
class Second {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from Main)
Student myObj = new Student();
System.out.println("Name: " + myObj.fname);
System.out.println("Age: " + myObj.age);
System.out.println("Graduation Year: " + myObj.graduationYear);
myObj.study(); // call abstract method
}
}
출처 : W3Schools Online Web Tutorials