1OOP in JavaNelson Padua-PerezChau-Wen TsengDepartment of Computer ScienceUniversity of Maryland, College ParkObject Oriented Programming (OOP)OO PrinciplesAbstractionEncapsulation Abstract Data Type (ADT)Implementation independent interfacesData and operations on dataJavaMany language features supporting OOP2OverviewObjects & classReferences & alias“this” & “super” referenceConstructor & initialization blockGarbage collection & destructorModifiersPublic, Private, ProtectedStatic FinalObject & ClassObjectAbstracts away (data, algorithm) detailsEncapsulates data Instances exist at run timeClassBlueprint for objects (of same type)Exists at compile time3References & AliasesReferenceA way to get to an object, not the object itselfAll variables in Java are references to objectsAliasMultiple references to same object“X == Y“ operator tests for alias X.equals(Y) tests contents of object (potentially)Object ZReference XReference YReferences & Aliases – IssuesCopyingReferencesX = new Object();Y = X; // Y refers to same object as XObjectsX = new Object();Y = X.clone(); // Y refers to different objectModifying objectsX = new Object();Y = X;X.change(); // modifies object for Y4“this” ReferenceDescriptionReserved keywordRefers to object through which method was invokedAllows object to refer to itselfUse to refer to instance variables of object“this” Reference – Exampleclass Node {value val1;value val2;void foo(value val2) {… = val1; // same as this.val1 (implicit this) … = val2; // parameter to method… = this.val2; // instance variable for objectbar( this ); // passes reference to object}}5InheritanceDefinitionRelationship between classes when state and behavior of one class is a subset of another classTerminologySuperclass / parent ⇒ More general classSubclass ⇒ More specialized classForms a class hierarchyHelps promote code reuse“super” ReferenceDescriptionReserved keywordRefers to superclassAllows object to refer to methods / variables in superclassExamplessuper.x // accesses variable x in superclasssuper() // invokes constructor in superclasssuper.foo() // invokes method foo() in superclass6ConstructorDescriptionMethod invoked when object is instantiatedHelps initialize objectMethod with same name as class w/o return typeImplicitly invokes constructor for superclassIf not explicitly includedConstructor – Exampleclass foo {foo() { … } // constructor for foo}class bar extends foo {bar() { // constructor for bar// implicitly invokes foo() here…}}class bar2 extends foo {bar2() { // constructor for barsuper(); // explicitly invokes foo() here}}7Initialization BlockDefinitionBlock of code used to initialize static & instance variables for classMotivationEnable complex initializations for static variablesControl flowExceptionsShare code between multiple constructors for same classInitialization Block Types Static initialization blockCode executed when class loaded Initialization blockCode executed when each object created (at beginning of call to constructor)Exampleclass foo {static { A = 1; } // static initialization block { A = 2; } // initialization block}8Variable InitializationVariables may be initializedAt time of declarationIn initialization blockIn constructorOrder of initialization1. Declaration, initialization block(in the same order as in the class definition) 2. ConstructorVariable Initialization – Exampleclass Foo {static { A = 1; } // static initialization block static int A = 2; // static variable declarationstatic { A = 3; } // static initialization block { B = 4; } // initialization blockprivate int B = 5; // instance variable declaration{ B = 6; } // initialization blockFoo() { // constructorA = 7;B = 8;} // now A = 7, B = 8} // initializations executed in order of number9Garbage CollectionConceptsAll interactions with objects occur through reference variablesIf no reference to object exists, object becomes garbage (useless, no longer affects program)Garbage collectionReclaiming memory used by unreferenced objectsPeriodically performed by JavaNot guaranteed to occurOnly needed if running low on memoryDestructorDescriptionMethod with name finalize()Returns void Contains action performed when object is freedInvoked automatically by garbage collectorNot invoked if garbage collection does not occurUsually needed only for non-Java methodsExampleclass foo {void finalize() { … } // destructor for foo}10Method OverloadingDescriptionSame name refers to multiple methodsSources of overloadingMultiple methods with different parametersConstructors frequently overloadedRedefine method in subclassExampleclass foo {foo() { … } // constructor for foofoo(int n) { … } // 2ndconstructor for foo}PackageDefinitionGroup related classes under one nameHelps manage software complexitySeparate namespace for each packagePackage name added in front of actual namePut generic / utility classes in packagesAvoid code duplicationExamplepackage edu.umd.cs; // name of package11Package – Import ImportMake classes from package available for useJava APIjava.* (core)javax.* (optional)Exampleimport java.util.Random; // import single classimport java.util.*; // all classes in package… // class definitionsScopeScopePart of program where a variable may be referencedDetermined by location of variable declarationBoundary usually demarcated by { } Examplepublic MyMethod1() {int myVar; myVar accessible in... method between { }}12Scope – ExampleExamplepackage edu.umd.cs ;public class MyClass1 {public void MyMethod1() {...}public void MyMethod2() {...}}public class MyClass2 {}MethodMethodClassPackageClassScopesModifierDescriptionJava keyword (added to definition)Specifies characteristics of a language construct(Partial) list of modifiersPublic / private / protectedStaticFinalAbstract13Modifier – Examplespublic class foo { private static int count;private final int increment = 5;protected void finalize { … }}public abstract class bar {abstract int go() { … }}Visibility ModifierPropertiesControls access to class membersApplied to instance variables & methodsFour types of access in JavaPublic Most visibleProtectedPackageDefault if no modifier specifiedPrivate Least visible14Visibility Modifier – Where Visible“public”Referenced anywhere (i.e., outside package)“protected”Referenced within package, or by subclasses outside packageNone specified (package)Referenced only within package“private”Referenced only within class
View Full Document