90 likes | 205 Views
Polymorphism. Overriding Methods refers to when a method in a child class has the same name as a method in a parent class. (know the difference: Overloading Methods refers to two methods in the same class that have the same name.)
E N D
Polymorphism • Overriding Methods refers to when a method in a child class has the same name as a method in a parent class. • (know the difference: Overloading Methods refers to two methods in the same class that have the same name.) • Sometimes, you create an object of the parent class, but assign it a value of the child class. This is called polymorphism. • When an overridden method in one of those classes is then called, Java decides at run-time which method to call. This run-time decision by Java is called dynamic binding.
Open: • Animal • Dog • Cat • PolymorphismClient
for-each loop • When going through (“traversing”) every element in an array or ArrayList, an efficient way to do so is by using a for-each loop. • Syntax: for (type element : array) { // body of loop } • Demo: ForEachLoopDemo
Static Methods • A static method can be called by using the name of the class itself. You do not need to create an object in order to call the method. • We have been using static methods for a long time: SavitchIn.readLine(); Math.pow(), etc. • This explains why you don’t have to “connect” (create an object of) the SavitchIn class in order to use it. • Open: StaticMethodClass, StaticMethodClient
Static variables • A variable can also be declared with the keyword static • Just like a static method, a static variable is not accessed through an object. It is accessed by using the name of the class itself. • A static variable is also known as a class variable. • Example: see StaticMethodClass & StaticMethodClient
Arrays of Objects • An array is not limited to holding just ints, or chars, or Strings, etc. • An array can hold objects. • Remember, when you connect to (instantiate) a class, you create an object, for example: Numbers x = new Numbers(); • In this example, x is an object. • Demo: Person, ArrayOfObjectsDemo
Types of errors • There are 3 types of errors: • Compiler error: An error that the compiler will point out to you before you can run it • Run-time error: Will not be noticed by the compiler; will crash the program when it runs • Logic Error: does not cause either of the above errors, but makes your program run in a way you do not want it to
Restricting the values in an Arraylist • By default, an ArrayList can store any type of Object. • You can, if you wish, restrict the type of thing that an ArrayList can hold, by using the < > symbols. • Example: ArrayList<Person> z = new ArrayList<Person>;
Assignment • Continue working on Practice Tests and the Case Study.