Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.

Similar presentations


Presentation on theme: "Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding."— Presentation transcript:

1 Chapter 9: Continuing Classes By Matt Hirsch

2 Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding A. Super III. Factoring with Inheritance IV. Superclasses as Parameters

3 Table Of Contents Cont. 3.Abstract Classes 4.Interfaces 5.Exception Handling I. Try, Catch II. Throws 6.Review

4 Static Fields and Methods Fields: Belong to the class as a whole, therefore each object of the class shares the same copy. Example: private static int numObjects = 0; Methods: Can be used without calling them through an object. Ex: public static void main(String[] args)

5 Why Use Static? Without static fields, if a shared value changes, each object of the class has to update its own copy, which is unnecessarily complicated and time consuming. Static methods can be accessed without using an object.

6 Examples Population: Whoever you are, there are the same amount of people in the world, therefore we all share the same value. Mass action: A species goes extinct as a whole. There are no survivors.

7 There’s a Catch… Because they are not referring to a specific object of the class, static fields and methods can’t access instance fields or methods. However, they may access static fields and methods, because they too belong to the entire class as a whole. Instance methods may access static fields and methods freely.

8 Example Class public class Animal { private static int population = 0; private boolean alive = true; public Animal() { population++; } public boolean isAlive() { return alive; } public void die() { if (alive) { alive = false; if (population > 0) population--; } } public static void extinct() { population = 0; } }

9 Inheritance Classes may “inherit”, or take on the features of other classes, and add new features or override old ones. After the class header type the keyword extends followed by the class to inherit. public class SubClass extends SuperClass { // put new fields and methods here, or override old ones }

10 Why Use Inheritance? To reuse a class without having to remake it. To factor features of 2 or more similar classes into 1 superclass. To store objects of varying classes to a variable of 1 superclass, or pass them where an object of the superclass is expected.

11 Object is Java for God The class Object is the root of the entire Java hierarchy. All classes must extend it. If a class does not have a superclass, it will be assumed it is extending Object. Therefore, any object can be used where Object is expected. There isn’t any way to avoid this. Live with it.

12 Recycle Code with Inheritance Since a subclass takes on all of the features of its superclass, it need only specify changes to the original class. You may either add new features to the class, or override old features.

13 Examples Ants have all the requirements to be animals, therefore they are a subclass of Animal because they have all of the features of an animal, plus a few more.

14 Example Class public class Ant extends Animal { public void reproduceAndDie() { if (isAlive()) { Ant baby = new Ant(); die(); } } }

15 Overriding A subclass may also make old features of the superclass have new functionality. This is called overriding. To override a method simply create a method header, and put the new contents inside it. A method with final in its header may not be overridden.

16 Super To access a method of the superclass, for which there is a method of the same name in the subclass, use “ super. ” and the method name. Works much like this, but refers to the superclass. This is usually used when overriding methods. A call to super must be the first line of the method. You may also use super() to refer to the superconstructor, much like this().

17 Factoring with Inheritance If multiple classes have similarities you can bind them together with a common superclass which contains these similarities. For example, Ants, monkeys, and humans all have the features of an animal, therefore all of their classes would extend the Animal class.

18 Example Classes public class Shark extends Animal { public void eat() { if (isAlive()) // omnomnomnom! }} class Worm extends Animal { public void burrow() { if (isAlive()) // burrow! }}

19 Superclasses as Parameters An object of a subclass may be stored in a variable of a superclass, passed to a method where a superclass is expected, or returned from a method that returns a superclass. However, it may only use the features of that superclass. The plus side is, this increases flexibility, as multiple subclasses can be passed to the same place.

20 Catches For reasons of reducing complexity, each class may have only 1 superclass. All classes must have Object as the origin of their inheritance hierarchy. A subclass may not access private features of the superclass. However, protected features are accessible to the class and subclasses.

21 Abstract Classes Abstract classes are classes which represent a vague concept of a class, therefore since they are incomplete they can’t be instantialized. The only way to use them is to extend them and fill in all incomplete features. Use abstract in the class header to create an abstract class.

22 Why Abstract? To represent incomplete ideas which must be filled in. Abstract classes may have abstract methods, which are method headers with abstract, followed by a ;. They may be called as if they were complete. All non-abstract subclasses of an abstract class must provide functional methods for every abstract method in it.

23 Example A human and a cat are animals, yet nothing can be just an animal and nothing more, therefore Animal is an abstract class.

24 Example Classes public abstract class Mammal extends Animal { public abstract void eat(); } class Wolf extends Mammal { public void eat() { // eat meat } class Sheep extends Mammal { public void eat() { // eats plants }

25 Interfaces A list of instance methods every class that uses it should have. Type public interface, the name, and put method headers followed by ; s within {} ’s. May contain fields, however, they are all assumed to be static final. A class puts implements Interface to use an interface and be able to be stored as a variable of that interface.

26 Interfaces Cont. All implementing classes must have all of the methods specified within the interface. Multiple interfaces may be implemented by 1 class by separating them with, s. Interfaces may extend other interfaces by putting the extends phrase in their header.

27 Why Interfaces? To tie together multiple unrelated classes with similarities. To allow classes to have elements of having multiple superclasses, without actually extending 2 classes. To increase argument flexibility, much like an abstract class.

28 Example Situations where classes have similarities, but not 1 common ancestor class. Or situations where a class has elements of multiple classes. For example, some animals are predators while some aren’t, therefore Predator is an interface instead of an abstract class. Killers kill animals while predators kill and eat their victims, therefore Predator is a subinterface of Killer.

29 Example Interfaces public interface Killer { public void kill(Prey a); } interface Predator extends Killer { public void eatPrey(Prey p); } interface Prey { public boolean isAlive(); public void die(); public void eatMe(); }

30 Example Classes public class KillerWolf extends Wolf implements Predator { public void kill(Prey p) { if (p.isAlive()) p.die(); } public void eatPrey(Prey p) { kill(p); p.eatMe(); } class EdibleSheep extends Sheep implements Prey { // isAlive() and die() were already in the superclass public void eatMe() { // omnomnomnom! }

31 Catches All non-abstract implementing classes must contain all of the methods specified in the interface. If an abstract class doesn’t contain a method it become abstract. Implementing classes are also responsible for the methods of the superinterfaces too. Variables of an interface must be instantiated as an object of an implementing class, and may only use the methods of the interface.

32 Exception Handling Sometimes in a program things go wrong, called errors, or something unexpected occurs, exceptions. There are 2 ways to handle them: if statements or try, catch blocks.

33 Throwable try blocks are code segments checked for throwable condition, which are thrown to catch blocks to handle them based on their class. An object must be of or of a subclass of Throwable to be thrown. Throwable has 2 immediate subclasses, Error and Exception. This makes it the root of the error and exception hierarchy.

34 Exceptions All exceptions are subclasses of the class Exception. When an exception occurs, an object of the specific exception’s class is created and is “thrown” to a part of the program that handles it. Either the machine or the programmer can specify when these are thrown. To throw an exception: throw new (String message);

35 Try, Catch For code segments that the remainder of should be skipped over if an exception occurs, use a try block. Follow it with catch( e) and a block. Inside the block, perform actions to handle the exception with the object e. Since subclasses can be passed where a superclass is expected, this can also work with catch blocks.

36 Example Segment try { int ans = 1 / 0; } catch (ArithmeticException e) { e.printStackTrace(); System.out.println(“Zero division error!\n” + e.getMessage()); }

37 Throws A method with throws in its method header will transfer the responsibility of catching its exceptions of that class to the method that called it.

38 Review 1.What keyword indicates a method that may not be overridden? A. const B. final C. abstract 2.What is the difference between an interface and an abstract class with only abstract methods? A. A class may implement several interfaces. B. A class may inherit only 1 class, therefore limiting the (very) abstract class. C. BOTH!

39 Answers 1: B. 2: C.

40 Review Assignment: Create an abstract class to represent all jobs, each with a certain salary and an abstract method to represent getting pay. Create at least 2 subclasses, each of which has a variable to represent pay and adds it each pay.


Download ppt "Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding."

Similar presentations


Ads by Google