Everything You Ever Wanted To Know About Java O-OWhat is a class?ClassesWhy inheritance?What are abstract classes for?InterfacesDeclarations and assignmentsWhat are interfaces for?Inner Classes IInner Classes IIWhat are inner classes for?Enumerationsenums are classesEnums really are classesOther features of enumsUsing generic classesDefining generic classesAccessProper use of fieldsComposition and inheritanceConstructorsConstructor chainingProper use of constructorsReferencesMethods IMethods IIMethods IIIGeneric methods with wildcardsvarargsProper use of methods IProper use of methods IIProper use of polymorphismProgram designThe EndJan 14, 2019Everything You Ever Wanted To Know About Java O-O2What is a class?A class is primarily a description of objects, or instances, of that classA class contains one or more constructors to create objectsA class is a typeA type defines a set of possible values, and operations on those valuesThe type of an object is the class that created itBut a class can also contain information about itselfAnything declared static belongs to the class itselfStatic variables contain information about the class, not about instances of the classStatic methods are executed by the class, not by instances of the classAnything not declared static is not part of the class, and cannot be used directly by the classHowever, a static method can create (or be given) objects, and can send messages to them3Classesclass MyClass extends ThatClass implements SomeInterface, SomeOtherInterface {...}A top-level class can be public or package (default)A class can be final, meaning it cannot be subclassedA class subclasses exactly one other class (default: Object)A class can implement any number of interfacesabstract class MyClass extends ThatClass implements SomeInterface, SomeOtherInterface {...}Same rules as above, except: An abstract class cannot be finalA class must be declared abstract if:It contains abstract methodsIt implements an interface but does not define all the methods of that interfaceAny class may be declared to be abstractAn abstract class can (and does) have constructorsYou cannot instantiate an abstract class4Why inheritance?Java provides a huge library of pre-written classesSometimes these classes are exactly what you needSometimes these classes are almost what you needIt’s easy to subclass a class and override the methods that you want to behave differentlyInheritance is a way of providing similar behavior to different kinds of objects, without duplicating codeYou should extend a class (and inherit from it) only if:Your new class really is a more specific kind of the superclass, a ndYou want your new class to have most or all of the functionality of the class you are extending, andYou need to add to or modify the capabilities of the superclassYou should not extend a class merely to use some of its featuresComposition is a better solution in this case5What are abstract classes for?Abstract classes are suitable when you can reasonably implement some, but not all, of the behavior of the subclassesExample: You have a game in which various kinds of animals move around and do thingsAll animals can move(), eat(), drink(), hide(), etc.Since these are identical or similar, it makes sense to have a default move() method, a default drink() method, etc.If you have a default draw() method, what would it draw?Since you probably never want an Animal object, but just specific animals (Zebra, Lion, etc.), you don’t need to be able to instantiate the Animal classMake Animal abstract, with an abstract void draw() method6Interfacesinterface MyInterface extends SomeOtherInterface {...}An interface can be public or packageAn interface cannot be finalA class can implement any number of interfacesAn interface can declare (not define) methodsAll declared methods are implicitly public and abstractAn interface can define fields, classes, and interfacesFields are implicitly static, final, and publicClasses are implicitly static and publicAn interface cannot declare constructorsIt’s OK (but unnecessary) to explicitly specify implicit attributes7Declarations and assignmentsSuppose class Cat extends Animal implements Pet {...} and class Persian extends Cat {...} and Cat puff = new Cat();Then the following are true:puff instanceof Cat, puff instanceof Animal, puff instanceof PetThe following is not true: puff instanceof PersianTo form the negative test, say !(puff instanceof Persian)The following declarations and assignments are legal:Animal thatAnimal = puff;Animal thatAnimal = (Animal)puff; // same as above, but explicit upcastPet myPet = puff; // a variable can be of an interface typePersian myFancyCat = (Persian)puff; // does a runtime checkThe following is also legal:void feed(Pet p, Food f) {...} // interface type as a parameter8What are interfaces for?Inheritance lets you guarantee that subclass objects have the same methods as their superclass objectsInterfaces let you guarantee that unrelated objects have the same methodsProblem: Your GUI has an area in which it needs to draw some object, but you don’t know yet what kind of object it will beSolution:Define a Drawable interface, with a method draw()Make your tables, graphs, line drawings, etc., implement Drawable In your GUI, call the object’s draw() method (legal for any Drawable object)If you didn’t have interfaces, here’s what you would have to do:if (obj instanceof Table) ((Table)obj).draw();else if (obj instanceof Graph) ((Graph)obj).draw();else if (obj instanceof LineDrawing) ((LineDrawing)obj).draw(); // etc.Worse, to add a new type of object, you have to change a lot of code9Inner Classes IInner classes are classes declared within another classA member class is defined immediately within another classA member class may be staticA member class may be abstract or final (but not both)A member class may be public, protected, package, or privateA local class is declared in a constructor, method, or initializer blockA local class may be abstract or final (but not both)A local class may access only final variables in its enclosing codeAn anonymous class is a special kind of local class10Inner Classes IIAn anonymous inner class is a kind of local classAn
View Full Document