Pokazywanie postów oznaczonych etykietą overriding. Pokaż wszystkie posty
Pokazywanie postów oznaczonych etykietą overriding. Pokaż wszystkie posty

9 mar 2010

Overriding i overloading

Following code fragment is given (Java 5):

1: class Human {
2:
Human getIt() {
3:
return this;
4:
}
5:
}
6:
7:
class Worker extends Human {
8:
// insert a single method here
9:
}

Which of the following methods would compile if inserted at line 8

Human getIt() { return this; }
Worker getIt() { return this; }
Object getIt() { return this; }
int getIt() { return 1; }
int getIt(int x) { return 1; }
Object getIt(int x) { return this; }


28 lut 2010

Zasady overriding

  1. Lista argumentów musi dokładnie pasować. ( ?)
  2. Taki sam zwracany typ lub subtyp!
  3. Modyfikator dostępu nie może być bardziej restrykcyjny!
  4. Modyfikator dostępu może być mniej restrykcyjny.
  5. jeżeli klasy base i subclass są w tym samym pakiecie to można override metody nie oznaczone private lub final.
  6. Jeżeli klasy base i subclass są w różnych pakietach to można override metody nie oznaczone final i oznaczone public lub protected!
  7. Metoda nadpisująca może rzucać unchecked(runtime) wyjątkiem,jakimkolwiek.
  8. metoda nadpisująca nie może rzucać wyjątkiem(checked) zupełnie nowym lub bardziej ogólnym od metody nadpisywanej!
  9. metoda nadpisująca może rzucać wyjątkami mniej ogólnymi lub liczbebnością mniej
  10. metoda nadpisująca nie musi throw jakiekokolwiek wyjątku!
  11. Nie możeż nadpisywać metod finalnych.
  12. Nie możesz nadpiywać metod static!
  13. Jeżeli metoda nie może nie być dziedziczona to nie może być nadpisywana (np private method in base class)



public class Base {

public void publicMethodInBase(){}
public void methodWithException() throws Exception{}
public void methodWithManyExceptions()throws IOException,NotSerializableException{}

public int intReturnMethod(){return 1;}
public void intArgMethod(int x){};


}


public class Subclass extends Base{

/*Bardziej restrykcyjny mod dostępu !*/
//!protected void publicMethodInBase(){}

@Override /*Ob bo wężwzy exception*/
public void methodWithException() throws IOException{}

/*Jest wiecej wyjątków ale węższe od Exception*/
public void methodWithException() throws IOException,NotSerializableException{}

public void methodWithException() {} //ok, bo mniej wyjątków

/*Zonk bo szerszy exception!!*/
//!public void methodWithManyExceptions()throws Exception{}

//!public long intReturnMethod(){return 1;} //zonk bo inny return!

/*To nie overriding lecz overloading!*/
public void intArgMethod(long x){};
}