-
Inheritance and PolymorphismJava 2022. 2. 9. 21:23
자바의 상속과 다형성에 대해 정리하였습니다.
< Introducing Inheritance >
Java class can inherit traits from another class.
The object-oriented principle of inheritance saves us the headache of redefining the same class members all over again.- Parent class, superclass, and base class refer to the class that another class inherits from.
- Child class, subclass, and derived class refer to a class that inherits from another class.
For Example)
Suppose we are building a Shape class in Java. We might give it some points in 2D, a method for calculating the area, and another method for displaying the shape. But what happens if we want a class for a triangle that has some triangle-specific methods? Do we need to redefine all of the same methods that we created for Shape?
No! (Phew.) Lucky for us, a Java class can also inherit traits from another class. Because a triangle is a Shape , we can define Triangle so that it inherits fields and methods directly from Shape. A reference of type Shape can refer to an object of Shape or an object of triangle
< Inheritance in Practice >
To define a child class so that it inherits from a parent class, use the keyword extends.
When we use inheritance to extend a subclass from a superclass, we create an “is-a” relationship from the subclass to the superclass.Example)
class Shape { // Shape class members } class Triangle extends Shape { // additional Triangle class members }
: Triangle has inherited traits from Shape, meaning it copied over class members from Shape.
< Inheriting the Constructor >
In child class, to use the parent class's constructor, use super( )
super( ) method means the parent class's constructor!- If you don't use super( ) when writing a constructor of a child class, Java will automatically (and secretly) call super() as the first line of your child class constructor.
Example : Let’s say Shape has a numSides field that is set by passing an integer into the constructor.
class Triangle extends Shape { Triangle() { super(3); } // additional Triangle class members } // It is also possible to write a constructor without making a call to any super() constructor: class Triangle extends Shape { Triangle() { this.numSides = 3; } // additional Triangle class methods }
< Parent Class Aspect Modifiers >
If a parent class have private members, child class can't inherit the members.
But there is another access modifier we can use to keep a parent class member accessible to its child classes and to files in the package it’s contained in+. The `final` keyword in Java is used to define constants, methods, or classes that cannot be changed or overridden.
// Variables final int MAX_VALUE = 100; // Methods class Parent { final void showMessage() { System.out.println("This is a final method."); } } // Classes final class Constants { // Class contents }
< Introducing Polymorphism >
Polymorphism, which derives from Greek meaning “many forms”, allows a child class to share the information and behavior of its parent class while also incorporating its own functionality.
These benefits are particularly helpful when we want to develop our own Java packages for other developers to import and use.The main advantages of polymorphic programming:
- Simplifying syntax
- Reducing cognitive overload for developers
Example : if Orange is a Fruit through inheritance, you can then use Orange in the same contexts as Fruit
String makeJuice(Fruit fruit) { return "Apple juice and " + fruit.squeeze(); } // inside main() Orange orange = new Orange(); System.out.println(juicer.makeJuice(orange));
< >
Method Overriding - parent class methods in a child class : use @Override keyword
We can give a single method slightly different meanings for different classes.- @Override informs the compiler that we want to override a method in the parent class.
If the method doesn’t exist in the parent class, we’ll get a helpful error when we compile the program.
Example : modify printBalance() method.
class BankAccount { protected double balance; public BankAccount(double balanceIn){ balance = balanceIn; } public void printBalance() { System.out.println("Your account balance is $" + balance); } } class CheckingAccount extends BankAccount { public CheckingAccount(double balance) { super(balance); } @Override public void printBalance() { System.out.println("Your checking account balance is $" + balance); } }
+. we can also use the super keyword to call the methods of a parent class.
class CheckingAccount extends BankAccount { public CheckingAccount(double balance) { super(balance); } @Override public void printBalance() { System.out.println("Your checking account balance is $" + balance); } public void checkBalances() { // calls method from CheckingAccount printBalance(); // calls method from BankAccount super.printBalance(); } public static void main(String[] args) { CheckingAccount myCheckings = new CheckingAccount(5000); myCheckings.checkBalances(); } } // Your checking account balance is $5000 // Your account balance is $5000
< Using a Child Class as its Parent Class >
With polymorphism , we can use a child class object where an object of its parent class is expected.
- To do so, instantiate a child class object as a member of the parent class.
Example)
BankAccount kaylasAccount = new CheckingAccount(600.00);
: We can use kaylasAccount as if it were an instance of BankAccount, in any situation where a BankAccount object would be expected.
(This would be true even if kaylasAccount were instantiated as a CheckingAccount, but using the explicit child as parent syntax is most helpful when we want to declare objects in bulk.)
+. But because method overriding is handled at runtime, if we call printBalance(), we’ll see something CheckingAccount specific:
Your checking account balance is $600.00
This is because at runtime, kaylasAccount is recognized as the CheckingAccount it is.
So, what if CheckingAccount has a method transferToSavings() that BankAccount does not have? Can kaylasAccount still use that method?
Well, no. The compiler believes that kaylasAccount is just a BankAccount that doesn’t have some fancy child class transferToSavings() method, so it would throw an error.
< Child Classes in Arrays and ArrayLists >
We can put instances of different classes that share a parent class together in an array or ArrayList.
Example)
Monster dracula, wolfman, zombie1; dracula = new Vampire(); wolfman = new Werewolf(); zombie1 = new Zombie(); Monster[] monsters = {dracula, wolfman, zombie1};
: we have a Monster parent class with a few child classes: Vampire, Werewolf, and Zombie.
< Child Classes in Method Parameters >
If we use a superclass reference as a method parameter, we can call the method using subclass reference arguments.
Example)
class ScaryStory { Monster monster; String setting; public ScaryStory(Monster antagonist, String place) { monster = antagonist; setting = place; } public void tellStory(){ System.out.println("Once upon a time, " + monster.name + " was at " + setting + " looking to scare some mortals."); } public static void main(String[] args) { Monster dracula; dracula = new Vampire("Dracula"); ScaryStory countDracula = new ScaryStory(dracula, "Dracula Castle"); countDracula.tellStory(); } }
: we used a reference of the class Vampire as our argument even though the constructor requested an object of class Monster. This is allowed because Vampire is a subclass of the Monster class.
'Java' 카테고리의 다른 글
Debugging (0) 2022.02.10 Static Variables and Methods (0) 2022.02.09 Math Methods (0) 2022.02.08 Access, Encapsulation, and Scope (0) 2022.02.08 String Methods (0) 2022.02.07