Instantiating a Class Accessing Object Members Packages The Access Modifiers

J.E.D.I.

1.3.5 Instantiating a Class

To instantiate a class, we simply use the new keyword followed by a call to a constructor. Lets go directly to an example. class ConstructObj { int data; ConstructObj { initialize data } public static void mainString args[] { ConstructObj obj = new ConstructObj; instantiation } }

1.3.6 Accessing Object Members

To access members of an object, we use the dot notation. It is used as follows: object.member The next example is based on the previous one with additional statements for accessing members and an additional method. class ConstructObj { int data; ConstructObj { initialize data } void setDataint data { this.data = data; } public static void mainString args[] { ConstructObj obj = new ConstructObj; instantiation obj.setData10; access setData System.out.printlnobj.data; access data } } The expected output of the given code is 10.

1.3.7 Packages

To indicate that the source file belongs to a particular package, we use the following syntax: packageDeclaration ::= package packageName; To import other packages, we use the following syntax: importDeclaration ::= import packageName.elementAccessed; Introduction to Programming II Page 14 J.E.D.I. With this, your source code should have the following format: [packageDeclaration] importDeclaration classDeclaration + Coding Guidelines: + indicates that there may be 1 or more occurrences of the line where it was applied to. Here is an example. package registration.reports; import registration.processing.; imports all classes in registration.processing package import java.util.List; import java.lang.; imported by default imports all classes in java.lang class MyClass { details of MyClass }

1.3.8 The Access Modifiers

The following table summarizes the access modifiers in Java. private defaultpackage protected public Same class Yes Yes Yes Yes Same package Yes Yes Yes Different package subclass Yes Yes Different package non-subclass Yes Table 1: Access Modifiers

1.3.9 Encapsulation