It's UWAweek 18 (1st semester, week 9)

help2005

This forum is provided to promote discussion amongst students enrolled in CITS2005 Object Oriented Programming.

Please consider offering answers and suggestions to help other students! And if you fix a problem by following a suggestion here, it would be great if other interested students could see a short "Great, fixed it!"  followup message.

How do I ask a good question?
Displaying selected article
Showing 1 of 112 articles.
Currently 1 other person reading this forum.


 UWA week 17 (1st semester, week 8) ↓
SVG not supported

Login to reply

👍?
helpful
12:17pm Mon 22nd Apr, Tin CP.

Annotations like @Override don't really change the code if I remember correctly, they just provide information to the compiler for error catching.

If a child method is intended to override a parent method, you should ALWAYS use @Override so the compiler can raise an error if it doesn't actually override anything (e.g. due to spelling error). Below, the two classes A and B have the same behaviour - in that they override the method hello() in the parent class Base. However, notice the intentional spelling mistake in A where we typed hwllo(). The code will not raise any error and the output will appear correct! But if we make the same mistake for class B then an error will be raised.

class Base {
    public void hello() {
        System.out.println("Base hello()");
    }
}

class A extends Base {
    public void hwllo() {
        System.out.println("A hello()");
    }
}

class B extends Base {
    @Override public void hello() {
        System.out.println("B hello()");
    }
}

class Main {
    public static void main(String[] args) {
        Base parent = new Base();
        A childA = new A();
        B childB = new B();
        parent.hello();
        childA.hwllo();
        childB.hello();
    }
}

You can find more annotations here https://www.geeksforgeeks.org/annotations-in-java/, some like @Deprecated tells the user that they shouldn't use a particular method (perhaps due to vulnerability or bad coding practice), but it doesn't change the behaviour of the code at all.

The University of Western Australia

Computer Science and Software Engineering

CRICOS Code: 00126G
Written by [email protected]
Powered by history
Feedback always welcome - it makes our software better!
Last modified  5:07AM Sep 06 2023
Privacy policy