Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Class A is referred to as the superclass or base class.
- //Class B is referred to as the subclass or derived class.
- class A {
- //constructor
- public A() {
- super();
- System.out.println("in A");
- }
- public A(int n) {
- super();
- System.out.println("in A int n");
- }
- }
- class B extends A {
- //constructor
- public B() {
- super();
- System.out.println("in B");
- }
- public B(int n) {
- super(n);
- System.out.println("in B int n");
- }
- }
- class C extends A {
- //constructor
- public C() {
- super();
- System.out.println("in B");
- }
- public C(int n) {
- this(); // this will execute the default constructor `public C() {`.
- System.out.println("in B int n");
- }
- }
- public class _05_ThisAndSuper {
- public static void main(String[] args) {
- /* ------------------------------------------------------ */
- // without using super()
- B obj = new B(); // → "in A" \n "in B"
- B obj2 = new B(2); // → "in A" \n "in B int n"
- // Why is it calling the constructor of the parent class ?
- //The thing is, every constructor in JAVA has a super(); method even if you don't see it.
- // By default, in every constructor the first statement is super();
- // super(); means that : call the constructor of the super class (here, class A), but which one? The default one (and not the parameterized one).
- //However, if we want to call the parameterized constructor we'll use super(n); i.e parameterized super. (see below)
- /* ------------------------------------------------------ */
- // with super(n);
- B obj4 = new B(2);
- /* Prints :
- in A int n
- in B int n
- */
- /* ------------------------------------------------------ */
- // but what is the super class of class A ?
- // by default class A is extended to Object i.e.
- // class A extends Object {..}
- /* ------------------------------------------------------ */
- // what if we want to execute both the constructors in a class ?
- // we'll use "this" keyword for that.
- C obj5 = new C(32);
- /* Prints :
- in A
- in B
- in B int n
- */
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement