JAVA
super keyword
seoca
2019. 1. 3. 08:31
Super
A super keyword refers to a parent class. Attaching () with super keyword means the constructor of the parent class. This ensures that no errors occur even if the default constructor for the parent class is lost.
Example Code I
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class Calculator { int a, b; public Calculator(){} //하위클래스가 호출될 때 자동으로 부모클래스의 생성자가 호출 //매개변수가 없는 기본생성자가 없으면 Error occur. //super 키워드 있으면 기본생성자는 생략가능 public Calculator(int a, int b){ this.a = a; this.b = b; } public void added() { System.out.println(this.a + this.b); } } class Subable extends Calculator { public Subable (int a, int b) { super(a, b); // ()는 부모클래스의 생성자를 의미 } public void sub() { System.out.println(this.a - this.b); } } public class CalculatorConstructorDemo5 { public static void main(String[] args) { Subable a1 = new Subable (15, 30); a1.added(); a1.sub(); } } |
Result
30
-10
Example Code II
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import java.util.*; import java.io.*; class BiCycle{ String define_me(){ return "a vehicle with pedals."; } } class MotorCycle extends BiCycle{ String define_me(){ return "a cycle with an engine."; } MotorCycle(){ System.out.println("Hello I am a motorcycle, I am "+ define_me()); String temp=super.define_me(); // to approach an method in super class System.out.println("My ancestor is a cycle who is "+ temp ); } } class Solution{ public static void main(String []args){ MotorCycle M=new MotorCycle(); } } | cs |
Result
Reference
생활코딩 https://opentutorials.org/course/1223/6126
Tool
https://colorscripter.com/
https://www.jdoodle.com/online-java-compiler