I was wondering what will be displied when whe create one type o object and inciaize with other, so the example is below:
class Mammal{int it = 12;public void move() throws Exception{System.out.println("mammal");}}class Cat extends Mammal{int it = 21;@Overridepublic void move(){System.out.println("cat");}}public class TestMammal{public static void main(String[] args) throws Exception{Mammal m = new Cat();Cat c = new Cat();c.move();m.move();// exception if not 'throws Exception' in main()System.out.println(m.it);System.out.println(c.it);}}
cat
cat
12
21
cat
12
21
answer:
general:
variables are shown from type of object, method from instancy of object,
detailed:
but (!) at runntime jvm is looking at method declaration into type of object,
and if we declare public void move() throws Exception
we are supposed to also : public static void main(String[] args) throws Exception
in other way we will get exception
/TestMammal.java:27: error: unreported exception Exception; must be caught or declared to be thrown
m.move();
^
1 error
m.move();
^
1 error
tested on:
Komentarze
Prześlij komentarz