W3schools - Inheritance
이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다
찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요
Inheritance
Why and when to use Inheritance?
- useful for code reusability!
It is possible to inherit attributes and methods from one class to anoter
Inheritance concept
-
subclass(child)
the class that inherits from anoter class
-
superclass(parent)
the class being inherited from
To inherit from a class use the “extends” keyword
class Vehicle{
protected String brand = “Ford”;
public void honk(){
System.out.println(“Tuut,tuut!”);
}
}
class Car extends Vehicle{
private String modelName = “Mustang”;
public static void main(String[] args){
Car myCar = new Car();
myCar.honk(); // call the method(from the Vehicle class)
on the myCar object
System.out.println(myCar.brand + “ ” + myCar.modelName);
}
}
Polymorphism
Means “many forms”, and it occurs when we have many classes that are related to each other by inheritance
It uses methods to perform different task
This allows us to perform a single action in different ways
class Animal{
public void animalSound(){
System.out.println(“The animal makes a sound”);
}
}
class Pig extends Animal{
public void animalSound(){
System.out.println(“The pig says : wee wee”);
}
}
class Dog extends Animal{
public void animalSound(){
System.out.println(“The dog says : bow wow”);
}
}
class Main{
public static void main(String[] args){
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}