objects constructors java essentials - kth · i the goal of object-oriented programming is ... i...
TRANSCRIPT
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Java EssentialsObject-Oriented Design, IV1350
1 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
ContentsArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
2 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
3 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Array
An array is appropriate if the number ofelements is fixed and known.int[] myArray = new int[5];
4 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
ListI It is better to use a java.util.List if
the number of elements is not both fixedand known.
1 import java.util.ArrayList;2 import java.util.List;34 public class Lists {5 public static void main(String[] args) {6 List myList = new ArrayList();7 myList.add("Hej");8 myList.add(3);9 }
10 }
I A List can contain objects of any class,this example stores a String (line 7) andan Integer (line 8).
5 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
ListI It is better to use a java.util.List if
the number of elements is not both fixedand known.
1 import java.util.ArrayList;2 import java.util.List;34 public class Lists {5 public static void main(String[] args) {6 List myList = new ArrayList();7 myList.add("Hej");8 myList.add(3);9 }
10 }
I A List can contain objects of any class,this example stores a String (line 7) andan Integer (line 8).
5 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Generic ListI The list content can be restricted to objects
of one specific class.I Adding <String> on line six specifies that
the list may only contain String objects.
I Adding <> on line seven specifies that thisholds also for the created ArrayList.
1 import java.util.ArrayList;2 import java.util.List;34 public class Lists {5 public static void main(String[] args) {6 List<String> myList =7 new ArrayList<>();8 myList.add("Hej");9 myList.add("Hopp");
10 }11 }
6 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Generic ListI The list content can be restricted to objects
of one specific class.I Adding <String> on line six specifies that
the list may only contain String objects.I Adding <> on line seven specifies that this
holds also for the created ArrayList.1 import java.util.ArrayList;2 import java.util.List;34 public class Lists {5 public static void main(String[] args) {6 List<String> myList =7 new ArrayList<>();8 myList.add("Hej");9 myList.add("Hopp");
10 }11 }
6 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Generic ListI The list content can be restricted to objects
of one specific class.I Adding <String> on line six specifies that
the list may only contain String objects.I Adding <> on line seven specifies that this
holds also for the created ArrayList.1 import java.util.ArrayList;2 import java.util.List;34 public class Lists {5 public static void main(String[] args) {6 List<String> myList =7 new ArrayList<>();8 myList.add("Hej");9 myList.add("Hopp");
10 }11 }
6 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Generic List (Cont’d)I A generic list can be iterated using a
for-each loop, see lines 11-13.1 import java.util.ArrayList;2 import java.util.List;34 public class Lists {5 public static void main(String[] args) {6 List<String> myList =7 new ArrayList<>();8 myList.add("Hej");9 myList.add("Hopp");
1011 for(String value : myList) {12 System.out.println(value);13 }14 }15 }
7 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
8 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
What is an Object?
I The goal of object-oriented programming isto declare classes that group data andmethods operating on that data.
I A class represents an abstraction, forexample person. An object of the classrepresents a specific instance of the class,for example the person you.
9 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
What is an Object?
I The goal of object-oriented programming isto declare classes that group data andmethods operating on that data.
I A class represents an abstraction, forexample person. An object of the classrepresents a specific instance of the class,for example the person you.
9 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
What is an Object?
I The goal of object-oriented programming isto declare classes that group data andmethods operating on that data.
I A class represents an abstraction, forexample person. An object of the classrepresents a specific instance of the class,for example the person you.
9 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code Example
I Create project in NetBeansI Create class
10 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code Example
I Create project in NetBeansI Create class
10 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Use static Very Restrictively
I Static fields are shared by all objects of theclass.
I If for example the account balance wasstatic, all accounts would have the samebalance. Such a program would be useless.
I Since fields can not be static, neither canmethods since static methods can onlyaccess static fields.
I Static fields and methods are normally notused at all, except in few very specialcases.
11 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Use static Very Restrictively
I Static fields are shared by all objects of theclass.
I If for example the account balance wasstatic, all accounts would have the samebalance. Such a program would be useless.
I Since fields can not be static, neither canmethods since static methods can onlyaccess static fields.
I Static fields and methods are normally notused at all, except in few very specialcases.
11 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Use static Very Restrictively
I Static fields are shared by all objects of theclass.
I If for example the account balance wasstatic, all accounts would have the samebalance. Such a program would be useless.
I Since fields can not be static, neither canmethods since static methods can onlyaccess static fields.
I Static fields and methods are normally notused at all, except in few very specialcases.
11 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Use static Very Restrictively
I Static fields are shared by all objects of theclass.
I If for example the account balance wasstatic, all accounts would have the samebalance. Such a program would be useless.
I Since fields can not be static, neither canmethods since static methods can onlyaccess static fields.
I Static fields and methods are normally notused at all, except in few very specialcases.
11 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Use static Very Restrictively
I Static fields are shared by all objects of theclass.
I If for example the account balance wasstatic, all accounts would have the samebalance. Such a program would be useless.
I Since fields can not be static, neither canmethods since static methods can onlyaccess static fields.
I Static fields and methods are normally notused at all, except in few very specialcases.
11 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Creating New Objects
Whenever we want to create a new account, wecreate a new object of the Account class. Thisis done with the operator new.Account acct = new Account(1234567, 100);
12 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Creating New Objects
Whenever we want to create a new account, wecreate a new object of the Account class. Thisis done with the operator new.Account acct = new Account(1234567, 100);
12 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code Example
I Create an Account object and use itI Demonstrate the debugger
13 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code Example
I Create an Account object and use itI Demonstrate the debugger
13 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
14 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Providing Initial ValuesI The constructor is used to provide initial
values to newly created objects.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }9 //The methods are not showed.
10 }
I The values passed to the constructor aresaved in the object’s fields on lines 6 and 7.
I Sending parameters to a constructor is justlike sending parameters to a method.
15 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Providing Initial ValuesI The constructor is used to provide initial
values to newly created objects.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }9 //The methods are not showed.
10 }
I The values passed to the constructor aresaved in the object’s fields on lines 6 and 7.
I Sending parameters to a constructor is justlike sending parameters to a method.
15 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Providing Initial ValuesI The constructor is used to provide initial
values to newly created objects.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }9 //The methods are not showed.
10 }
I The values passed to the constructor aresaved in the object’s fields on lines 6 and 7.
I Sending parameters to a constructor is justlike sending parameters to a method.
15 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Providing Initial ValuesI The constructor is used to provide initial
values to newly created objects.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }9 //The methods are not showed.
10 }
I The values passed to the constructor aresaved in the object’s fields on lines 6 and 7.
I Sending parameters to a constructor is justlike sending parameters to a method.
15 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Calling the Constructor
Account acct = new Account(1234567, 100);
I The constructor is invoked when an newobject is created.
I Parameters are passed to the constructorjust the same way parameters are passedwhen an ordinary method is called.
16 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Calling the Constructor
Account acct = new Account(1234567, 100);
I The constructor is invoked when an newobject is created.
I Parameters are passed to the constructorjust the same way parameters are passedwhen an ordinary method is called.
16 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Calling the Constructor
Account acct = new Account(1234567, 100);
I The constructor is invoked when an newobject is created.
I Parameters are passed to the constructorjust the same way parameters are passedwhen an ordinary method is called.
16 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The Variable thisThe variable this always refers to the currentobject.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }
I Lines 6 and 7 illustrate the use of this.
I this.balance on line 7 refers to thefield declared on line 3.
I balance on line 7 refers to theconstructor parameter declared on line 5.
I These are two different variables.
17 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The Variable thisThe variable this always refers to the currentobject.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }
I Lines 6 and 7 illustrate the use of this.I this.balance on line 7 refers to the
field declared on line 3.
I balance on line 7 refers to theconstructor parameter declared on line 5.
I These are two different variables.
17 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The Variable thisThe variable this always refers to the currentobject.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }
I Lines 6 and 7 illustrate the use of this.I this.balance on line 7 refers to the
field declared on line 3.I balance on line 7 refers to the
constructor parameter declared on line 5.
I These are two different variables.
17 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The Variable thisThe variable this always refers to the currentobject.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }
I Lines 6 and 7 illustrate the use of this.I this.balance on line 7 refers to the
field declared on line 3.I balance on line 7 refers to the
constructor parameter declared on line 5.I These are two different variables. 17 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The Variable thisThe variable this always refers to the currentobject.1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo, int balance) {6 this.acctNo = acctNo;7 this.balance = balance;8 }
I Lines 6 and 7 illustrate the use of this.I this.balance on line 7 refers to the
field declared on line 3.I balance on line 7 refers to the
constructor parameter declared on line 5.I These are two different variables. 17 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
More Than One Constructor1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo) {6 this(acctNo, 0);7 }89 public Account(long acctNo, int balance) {
10 this.acctNo = acctNo;11 this.balance = balance;12 }13 }
I We need more constructors if we do not alwaysprovide the same set of initialization parameters.
I The constructor on lines 5-7 is used when no initialbalance is specified.
I Calls constructor on lines 9-11, with balance = 0.
18 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
More Than One Constructor1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo) {6 this(acctNo, 0);7 }89 public Account(long acctNo, int balance) {
10 this.acctNo = acctNo;11 this.balance = balance;12 }13 }
I We need more constructors if we do not alwaysprovide the same set of initialization parameters.
I The constructor on lines 5-7 is used when no initialbalance is specified.
I Calls constructor on lines 9-11, with balance = 0.
18 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
More Than One Constructor1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo) {6 this(acctNo, 0);7 }89 public Account(long acctNo, int balance) {
10 this.acctNo = acctNo;11 this.balance = balance;12 }13 }
I We need more constructors if we do not alwaysprovide the same set of initialization parameters.
I The constructor on lines 5-7 is used when no initialbalance is specified.
I Calls constructor on lines 9-11, with balance = 0.18 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
More Than One Constructor1 public class Account {2 private long acctNo;3 private int balance;45 public Account(long acctNo) {6 this(acctNo, 0);7 }89 public Account(long acctNo, int balance) {
10 this.acctNo = acctNo;11 this.balance = balance;12 }13 }
I We need more constructors if we do not alwaysprovide the same set of initialization parameters.
I The constructor on lines 5-7 is used when no initialbalance is specified.
I Calls constructor on lines 9-11, with balance = 0.18 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
19 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
A Reference Is a Value
I The new operator returns a reference tothe newly created object.
I A reference can, like any other value, bestored in variables, sent to methods, sent toconstructors, etc.
I Whenever the new operator is used, a newobject with a new reference is created.Many bugs arise because wrong referenceis used.
20 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
A Reference Is a Value
I The new operator returns a reference tothe newly created object.
I A reference can, like any other value, bestored in variables, sent to methods, sent toconstructors, etc.
I Whenever the new operator is used, a newobject with a new reference is created.Many bugs arise because wrong referenceis used.
20 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
A Reference Is a Value
I The new operator returns a reference tothe newly created object.
I A reference can, like any other value, bestored in variables, sent to methods, sent toconstructors, etc.
I Whenever the new operator is used, a newobject with a new reference is created.Many bugs arise because wrong referenceis used.
20 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code ExampleI Passing referencesI It is impossible to follow the course without
understanding the following example.
21 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code ExampleI Passing referencesI It is impossible to follow the course without
understanding the following example.
21 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code ExampleI Passing referencesI It is impossible to follow the course without
understanding the following example.
21 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code ExampleI Passing referencesI It is impossible to follow the course without
understanding the following example.
21 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
22 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Exception Changes ExecutionI Method throwing exception is interrupted.
I Execution continues in catch block in callingmethod.
public class Main {public static void main(String[] args) {
try {ClassThatThrowsException ctte = new ClassThatThrowsException();System.out.println("before call to methodThatThrowsException");ctte.methodThatThrowsException(true);System.out.println("after call to methodThatThrowsException");
} catch (Exception e) {System.out.println("in catch block");
}}
}
public class ClassThatThrowsException {public void methodThatThrowsException(boolean throwException) throws Exception {
System.out.println("Before throw");if (throwException) {throw new Exception("Information about the exception");
}System.out.println("After throw");
}}
The code above prints the following.before call to methodThatThrowsExceptionBefore throwin catch block
23 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Exception Changes ExecutionI Method throwing exception is interrupted.I Execution continues in catch block in calling
method.
public class Main {public static void main(String[] args) {
try {ClassThatThrowsException ctte = new ClassThatThrowsException();System.out.println("before call to methodThatThrowsException");ctte.methodThatThrowsException(true);System.out.println("after call to methodThatThrowsException");
} catch (Exception e) {System.out.println("in catch block");
}}
}
public class ClassThatThrowsException {public void methodThatThrowsException(boolean throwException) throws Exception {
System.out.println("Before throw");if (throwException) {throw new Exception("Information about the exception");
}System.out.println("After throw");
}}
The code above prints the following.before call to methodThatThrowsExceptionBefore throwin catch block
23 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Exception Changes ExecutionI Method throwing exception is interrupted.I Execution continues in catch block in calling
method.public class Main {
public static void main(String[] args) {try {
ClassThatThrowsException ctte = new ClassThatThrowsException();System.out.println("before call to methodThatThrowsException");ctte.methodThatThrowsException(true);System.out.println("after call to methodThatThrowsException");
} catch (Exception e) {System.out.println("in catch block");
}}
}
public class ClassThatThrowsException {public void methodThatThrowsException(boolean throwException) throws Exception {
System.out.println("Before throw");if (throwException) {
throw new Exception("Information about the exception");}System.out.println("After throw");
}}
The code above prints the following.before call to methodThatThrowsExceptionBefore throwin catch block
23 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Exception Changes ExecutionI Method throwing exception is interrupted.I Execution continues in catch block in calling
method.public class Main {
public static void main(String[] args) {try {
ClassThatThrowsException ctte = new ClassThatThrowsException();System.out.println("before call to methodThatThrowsException");ctte.methodThatThrowsException(true);System.out.println("after call to methodThatThrowsException");
} catch (Exception e) {System.out.println("in catch block");
}}
}
public class ClassThatThrowsException {public void methodThatThrowsException(boolean throwException) throws Exception {
System.out.println("Before throw");if (throwException) {
throw new Exception("Information about the exception");}System.out.println("After throw");
}}
The code above prints the following.before call to methodThatThrowsExceptionBefore throwin catch block 23 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Exception Changes ExecutionI Method throwing exception is interrupted.I Execution continues in catch block in calling
method.public class Main {
public static void main(String[] args) {try {
ClassThatThrowsException ctte = new ClassThatThrowsException();System.out.println("before call to methodThatThrowsException");ctte.methodThatThrowsException(true);System.out.println("after call to methodThatThrowsException");
} catch (Exception e) {System.out.println("in catch block");
}}
}
public class ClassThatThrowsException {public void methodThatThrowsException(boolean throwException) throws Exception {
System.out.println("Before throw");if (throwException) {
throw new Exception("Information about the exception");}System.out.println("After throw");
}}
The code above prints the following.before call to methodThatThrowsExceptionBefore throwin catch block 23 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code Example
I The catch block need not be in callingmethod.
I Can be placed further up in the method callstack.
I Illustrated in the following code example.
24 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code Example
I The catch block need not be in callingmethod.
I Can be placed further up in the method callstack.
I Illustrated in the following code example.
24 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code Example
I The catch block need not be in callingmethod.
I Can be placed further up in the method callstack.
I Illustrated in the following code example.
24 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Runtime Exceptions
I All examples so far have been checkedexceptions.
I There are also runtime exceptions, whichinherits the classjava.lang.RuntimeException.
I Runtime exceptions do not have to bespecified in a throws clause.
25 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Runtime Exceptions
I All examples so far have been checkedexceptions.
I There are also runtime exceptions, whichinherits the classjava.lang.RuntimeException.
I Runtime exceptions do not have to bespecified in a throws clause.
25 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Runtime Exceptions
I All examples so far have been checkedexceptions.
I There are also runtime exceptions, whichinherits the classjava.lang.RuntimeException.
I Runtime exceptions do not have to bespecified in a throws clause.
25 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
26 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Javadoc
I Javadoc is used to generate html pageswith code documentation.
I It is strongly recommended to write Javadocfor all declarations (classes, interfaces,methods, fields etc) that are not private.
I A Javadoc comment is written between/** and */.
I The tags @param and @return are usedto document method parameters and returnvalues.
27 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Javadoc
I Javadoc is used to generate html pageswith code documentation.
I It is strongly recommended to write Javadocfor all declarations (classes, interfaces,methods, fields etc) that are not private.
I A Javadoc comment is written between/** and */.
I The tags @param and @return are usedto document method parameters and returnvalues.
27 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Javadoc
I Javadoc is used to generate html pageswith code documentation.
I It is strongly recommended to write Javadocfor all declarations (classes, interfaces,methods, fields etc) that are not private.
I A Javadoc comment is written between/** and */.
I The tags @param and @return are usedto document method parameters and returnvalues.
27 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Javadoc
I Javadoc is used to generate html pageswith code documentation.
I It is strongly recommended to write Javadocfor all declarations (classes, interfaces,methods, fields etc) that are not private.
I A Javadoc comment is written between/** and */.
I The tags @param and @return are usedto document method parameters and returnvalues.
27 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Code Example
Write Javadoc comments and generate htmlpages.
28 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
29 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
AnnotationsI Annotations provide information about a
piece of source code for the compiler, JVMor something else.
I Usually used for properties unrelated to thefunctionality of the source code, forexample to configure security, networkingor multithreading.
I Starts with the at sign, @, for example@SomeAnnotation.
I May take parameters, for example@SomeAnnotation(someString= ‘‘abc’’, someBoolean =true)
30 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
AnnotationsI Annotations provide information about a
piece of source code for the compiler, JVMor something else.
I Usually used for properties unrelated to thefunctionality of the source code, forexample to configure security, networkingor multithreading.
I Starts with the at sign, @, for example@SomeAnnotation.
I May take parameters, for example@SomeAnnotation(someString= ‘‘abc’’, someBoolean =true)
30 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
AnnotationsI Annotations provide information about a
piece of source code for the compiler, JVMor something else.
I Usually used for properties unrelated to thefunctionality of the source code, forexample to configure security, networkingor multithreading.
I Starts with the at sign, @, for example@SomeAnnotation.
I May take parameters, for example@SomeAnnotation(someString= ‘‘abc’’, someBoolean =true)
30 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
AnnotationsI Annotations provide information about a
piece of source code for the compiler, JVMor something else.
I Usually used for properties unrelated to thefunctionality of the source code, forexample to configure security, networkingor multithreading.
I Starts with the at sign, @, for example@SomeAnnotation.
I May take parameters, for example@SomeAnnotation(someString= ‘‘abc’’, someBoolean =true)
30 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
31 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Interface Is a Contract
I An interface is a contract. A classimplementing the interface must fulfill thecontract specified by the interface.
I The contract is specified as a set ofmethods. The implementing class mustprovide implementations for those methods.
I The methods must do what is intended inthe interface. This should be documentedin the interface.
I All declarations in an interface are alwayspublic.
32 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Interface Is a Contract
I An interface is a contract. A classimplementing the interface must fulfill thecontract specified by the interface.
I The contract is specified as a set ofmethods. The implementing class mustprovide implementations for those methods.
I The methods must do what is intended inthe interface. This should be documentedin the interface.
I All declarations in an interface are alwayspublic.
32 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Interface Is a Contract
I An interface is a contract. A classimplementing the interface must fulfill thecontract specified by the interface.
I The contract is specified as a set ofmethods. The implementing class mustprovide implementations for those methods.
I The methods must do what is intended inthe interface. This should be documentedin the interface.
I All declarations in an interface are alwayspublic.
32 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Interface Is a Contract
I An interface is a contract. A classimplementing the interface must fulfill thecontract specified by the interface.
I The contract is specified as a set ofmethods. The implementing class mustprovide implementations for those methods.
I The methods must do what is intended inthe interface. This should be documentedin the interface.
I All declarations in an interface are alwayspublic.
32 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Interface ExampleThe following interface defines the contract Write thespecified string to the log.
public interface Logger {/*** Writes the specified message to the log.* @param message This string is written* to the log.*/void log(String message);
}
The interface is implemented by the following class.
public class FileLogger implements Logger {...
public void log(String message) {//write to file
}}
33 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Interface ExampleThe following interface defines the contract Write thespecified string to the log.
public interface Logger {/*** Writes the specified message to the log.* @param message This string is written* to the log.*/void log(String message);
}
The interface is implemented by the following class.
public class FileLogger implements Logger {...
public void log(String message) {//write to file
}}
33 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Interface ExampleThe following interface defines the contract Write thespecified string to the log.
public interface Logger {/*** Writes the specified message to the log.* @param message This string is written* to the log.*/void log(String message);
}
The interface is implemented by the following class.
public class FileLogger implements Logger {...
public void log(String message) {//write to file
}}
33 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Interface ExampleThe following interface defines the contract Write thespecified string to the log.
public interface Logger {/*** Writes the specified message to the log.* @param message This string is written* to the log.*/void log(String message);
}
The interface is implemented by the following class.
public class FileLogger implements Logger {...
public void log(String message) {//write to file
}}
33 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The @Override AnnotationI The @Override annotation specifies
that the annotated method should beinherited from a superclass or interface.
I A compiler error will result if the method isnot inherited.
I Always use @Override for inheritedmethods since it eliminates the risk ofaccidentally specifying a new method.
I For example accidentally naming themethod logg instead of log in theimplementing class in the previousexample.
34 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The @Override AnnotationI The @Override annotation specifies
that the annotated method should beinherited from a superclass or interface.
I A compiler error will result if the method isnot inherited.
I Always use @Override for inheritedmethods since it eliminates the risk ofaccidentally specifying a new method.
I For example accidentally naming themethod logg instead of log in theimplementing class in the previousexample.
34 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The @Override AnnotationI The @Override annotation specifies
that the annotated method should beinherited from a superclass or interface.
I A compiler error will result if the method isnot inherited.
I Always use @Override for inheritedmethods since it eliminates the risk ofaccidentally specifying a new method.
I For example accidentally naming themethod logg instead of log in theimplementing class in the previousexample.
34 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The @Override AnnotationI The @Override annotation specifies
that the annotated method should beinherited from a superclass or interface.
I A compiler error will result if the method isnot inherited.
I Always use @Override for inheritedmethods since it eliminates the risk ofaccidentally specifying a new method.
I For example accidentally naming themethod logg instead of log in theimplementing class in the previousexample.
34 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
SectionArrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
35 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
InheritanceEverything in the superclass that is not private isalso present in the the subclass.public class Superclass {
public void methodInSuperclass() {System.out.println("Printed from methodInSuperclass");
}}
public class Subclass extends Superclass {public static void main(String[] args) {
Subclass subclass = new Subclass();subclass.methodInSuperclass();
}}
The program above prints the following.Printed from methodInSuperclass
36 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
InheritanceEverything in the superclass that is not private isalso present in the the subclass.public class Superclass {
public void methodInSuperclass() {System.out.println("Printed from methodInSuperclass");
}}
public class Subclass extends Superclass {public static void main(String[] args) {
Subclass subclass = new Subclass();subclass.methodInSuperclass();
}}
The program above prints the following.Printed from methodInSuperclass
36 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
InheritanceEverything in the superclass that is not private isalso present in the the subclass.public class Superclass {
public void methodInSuperclass() {System.out.println("Printed from methodInSuperclass");
}}
public class Subclass extends Superclass {public static void main(String[] args) {
Subclass subclass = new Subclass();subclass.methodInSuperclass();
}}
The program above prints the following.Printed from methodInSuperclass
36 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Override (Omdefiniera)I A method in the subclass with the same
signature as the method in the superclasswill override the superclass’ method.
I A method’s signature consists of its nameand parameter list.
I Overriding means that the overridingmethod will be executed instead of theoverridden.
I Do not confuse with overloading(överlagra), which is to have methods withsame name but different signatures, due todifferent parameter lists. This has nothingto do with inheritance.
37 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Override (Omdefiniera)I A method in the subclass with the same
signature as the method in the superclasswill override the superclass’ method.
I A method’s signature consists of its nameand parameter list.
I Overriding means that the overridingmethod will be executed instead of theoverridden.
I Do not confuse with overloading(överlagra), which is to have methods withsame name but different signatures, due todifferent parameter lists. This has nothingto do with inheritance.
37 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Override (Omdefiniera)I A method in the subclass with the same
signature as the method in the superclasswill override the superclass’ method.
I A method’s signature consists of its nameand parameter list.
I Overriding means that the overridingmethod will be executed instead of theoverridden.
I Do not confuse with overloading(överlagra), which is to have methods withsame name but different signatures, due todifferent parameter lists. This has nothingto do with inheritance.
37 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Override (Omdefiniera)I A method in the subclass with the same
signature as the method in the superclasswill override the superclass’ method.
I A method’s signature consists of its nameand parameter list.
I Overriding means that the overridingmethod will be executed instead of theoverridden.
I Do not confuse with overloading(överlagra), which is to have methods withsame name but different signatures, due todifferent parameter lists. This has nothingto do with inheritance.
37 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Override Examplepublic class Superclass {
public void overriddenMethod() {System.out.println("Printed from overriddenMethod" +
" in superclass");}
}
public class Subclass extends Superclass {@Overridepublic void overriddenMethod() {
System.out.println("Printed from overriddenMethod" +" in subclass");
}
public static void main(String[] args) {Subclass subclass = new Subclass();subclass.overriddenMethod();
}}
The program above prints the following.Printed from overriddenMethod in subclass
38 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
Override Examplepublic class Superclass {
public void overriddenMethod() {System.out.println("Printed from overriddenMethod" +
" in superclass");}
}
public class Subclass extends Superclass {@Overridepublic void overriddenMethod() {
System.out.println("Printed from overriddenMethod" +" in subclass");
}
public static void main(String[] args) {Subclass subclass = new Subclass();subclass.overriddenMethod();
}}
The program above prints the following.Printed from overriddenMethod in subclass
38 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
To Call the Superclasssuper is a reference to the superclass.public class Superclass {
public void overridenMethod() {System.out.println("Printed from Superclass");
}}
public class Subclass extends Superclass {public void overridenMethod() {
System.out.println("Printed from Subclass");super.overridenMethod();
}
public static void main(String[] args) {Subclass subclass = new Subclass();subclass.overridenMethod();
}}
The program above prints the following.Printed from SubclassPrinted from Superclass
39 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
To Call the Superclasssuper is a reference to the superclass.public class Superclass {
public void overridenMethod() {System.out.println("Printed from Superclass");
}}
public class Subclass extends Superclass {public void overridenMethod() {
System.out.println("Printed from Subclass");super.overridenMethod();
}
public static void main(String[] args) {Subclass subclass = new Subclass();subclass.overridenMethod();
}}
The program above prints the following.Printed from SubclassPrinted from Superclass
39 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
To Call the Superclasssuper is a reference to the superclass.public class Superclass {
public void overridenMethod() {System.out.println("Printed from Superclass");
}}
public class Subclass extends Superclass {public void overridenMethod() {
System.out.println("Printed from Subclass");super.overridenMethod();
}
public static void main(String[] args) {Subclass subclass = new Subclass();subclass.overridenMethod();
}}
The program above prints the following.Printed from SubclassPrinted from Superclass
39 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The assigned instance is executed, not the declared type.public class Superclass {
public void overriddenMethod() {System.out.println("Printed from overriddenMethod" +
" in superclass");}
}
public class Subclass extends Superclass {@Overridepublic void overriddenMethod() {
System.out.println("Printed from overriddenMethod" +" in subclass");
}
public static void main(String[] args) {Subclass subclass = new Subclass();subclass.overriddenMethod();Superclass superclass = new Subclass();superclass.overriddenMethod();
}}
The program above prints the following.Printed from overriddenMethod in subclassPrinted from overriddenMethod in subclass
40 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The assigned instance is executed, not the declared type.public class Superclass {
public void overriddenMethod() {System.out.println("Printed from overriddenMethod" +
" in superclass");}
}
public class Subclass extends Superclass {@Overridepublic void overriddenMethod() {
System.out.println("Printed from overriddenMethod" +" in subclass");
}
public static void main(String[] args) {Subclass subclass = new Subclass();subclass.overriddenMethod();Superclass superclass = new Subclass();superclass.overriddenMethod();
}}
The program above prints the following.Printed from overriddenMethod in subclassPrinted from overriddenMethod in subclass
40 / 40
Java Essentials
Arrays and Lists
Objects
Constructors
References
Exceptions
Javadoc
Annotations
Interfaces
Inheritance
The assigned instance is executed, not the declared type.public class Superclass {
public void overriddenMethod() {System.out.println("Printed from overriddenMethod" +
" in superclass");}
}
public class Subclass extends Superclass {@Overridepublic void overriddenMethod() {
System.out.println("Printed from overriddenMethod" +" in subclass");
}
public static void main(String[] args) {Subclass subclass = new Subclass();subclass.overriddenMethod();Superclass superclass = new Subclass();superclass.overriddenMethod();
}}
The program above prints the following.Printed from overriddenMethod in subclassPrinted from overriddenMethod in subclass
40 / 40