Presentation is loading. Please wait.

Presentation is loading. Please wait.

More on Classes & Arrays

Similar presentations


Presentation on theme: "More on Classes & Arrays"— Presentation transcript:

1 More on Classes & Arrays
Pepper With help from

2 Review - A Class Trace Exercise
What's wrong with the following program? public class SomethingIsWrong { public static void main(String[] args) { Rectangle myRect; myRect.width = 40; myRect.height = 50; System.out.println ("myRect's area is " + myRect.area()); } }

3 Class Extension Make sub-classes (put "extends " classname after class) Can use the entire extended class Can override methods This is how we use Fang's game class Can see all protected and public methods and variables

4 Class Extension - Super
Can choose to execute methods from the super class using super.methodname

5 Player Extension Make one player Extend to different player types
Example:

6 Abstraction If you know you will make a lower class, you don't have to implement all methods You can mark a class as abstract (public abstract class) and then put only the method headers. Compiler complains if the lower class does not implement it.

7 Interface Can create a type that has only abstract methods.
Basically a contract to implement interfaces Contains method headers with no code below it. Lower classes can implement many interfaces (but only extend one class) Implementing an interface means you promise (and the compiler checks) that you will implement the methods listed.

8 More on Arrays – For Each
Shortcut for loop through an array: for (variable to hold value : array name) Ex: int[] arr= {1,2,3,4}; int tot = 0; for (int x : arr) { tot = tot + x;} System.out.println(tot);

9 ArrayList An Array class Has methods you can use
Can make an array of anything using <type> ArrayList<String> myArr = new ArrayList<String>(); ArrayList<Player> guys = new ArrayList<Player>();

10 ArrayList Methods Methods
add( Object o ) - puts reference to object into ArrayList get( int index ) - retrieves object reference from ArrayList index position size() - returns ArrayList size remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list. indexOf( Object o) - finds the index in this list of the first occurrence of the specified element clear() - removes all of the elements

11 ArrayList of Players guys.add(new Player("Amy")); guys.add(new Player("Jim")); guys.


Download ppt "More on Classes & Arrays"

Similar presentations


Ads by Google