"Java 상속"의 두 판 사이의 차이

(새 문서: ==개요== ; Class 를 상속받아 다른 Class에서 활용할수 있다 ;;subclass (child) - the class that inherits from another class ;;superclass (parent) - the class being inhe...)
 
1번째 줄: 1번째 줄:
==개요==
==개요==
; Class 를 상속받아 다른 Class에서 활용할수 있다
; Class 를 상속받아 다른 Class에서 활용할수 있다
;;subclass (child) - the class that inherits from another class
;; subclass (child) - 어떤 Class를 상속받은 Class
;;superclass (parent) - the class being inherited from
;; superclass (parent) - 다른 Class에 상속해준 Class
;extends 라는 키워드를 쓰면 상속받을수 있다.
 
<syntaxhighlight lang='java' multi file=Vehicle.java>
class Vehicle {
  protected String brand = "Ford";        // Vehicle attribute
  public void honk() {                    // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}
 
 
</syntaxhighlight>
<syntaxhighlight lang='java' multi file=Car.java main>
class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {
 
    // Create a myCar object
    Car myCar = new Car();
 
    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();
 
    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}
</syntaxhighlight>

2021년 10월 5일 (화) 22:32 판

개요

Class 를 상속받아 다른 Class에서 활용할수 있다
subclass (child) - 어떤 Class를 상속받은 Class
superclass (parent) - 다른 Class에 상속해준 Class
extends 라는 키워드를 쓰면 상속받을수 있다.
class Vehicle {
  protected String brand = "Ford";        // Vehicle attribute
  public void honk() {                    // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}
class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}