Sie sind auf Seite 1von 10

Chapter 2: Objects, everything around you is an object. Object Oriented Concepts (4.

5 hrs) Chapter Objectives: Define what objects are and demonstrate how to create them. Recognize the states of object creation before and after the execution of the constructor. State the difference between objects, classes, methods, and data attribute. Describe when and how to make use of constructors. Point out the rules that describes the use of default constructors. Compare the difference between public and private access modifiers. Define what is encapsulation. Show the proper way of implementing encapsulation to a class. Design a Java source file layout Create and deploy a Jar file. Objects vs Classes What are Objects? Objects are anything that is real. It can be something that is conceptual or something that is physical. Anything around you right now are considered as objects, the chairs, tables, books, or even your papers. All these are objects. But objects are not just limited to physical objects like these physical things around us. If you look into a desktop application, you can also see objects. Using your favorite word processor you will see objects in them. Buttons, toolbars and even the work area or the dialog boxes all these are objects. Physical objects can be tangible or intangible, but they are all visible. Objects can also be something that is conceptual. Conceptual objects are objects that are not seen but they are actually there. These types of objects are also useful and they represent a set to data as well. An example of conceptual objects are errors, exceptions or events. Errors and exceptions will be discussed in a separate chapter as well as events. But to give us a little idea about these conceptual objects. Errors and exceptions are objects that is being thrown by your application every time that something goes wrong with it. While events are the things that happens when you trigger a GUI component, an example of which is a button press or a mouse drag. What are Classes? A class is the blue-print of an object. It is the declaration of data attributes and methods (also known as behavior) that each object will have every time an object is being instantiated. The term instantiate is synonymous with the term create. So, every time you instantiate an object, you are actually creating an object from a class and the said object will reside on the heap memory. You can create virtually unlimited number of objects from a class. Each objects has its own set of identity. This means that what ever changes takes place in one object, the other objects are unaffected with the changes. Within this book, we will use UML (Unified Modeling Language) diagrams to graphically represent a class. Consider this example: Person + name : String + age : int + showDetails() : void

Page 1 of 10

Prepared by: Lawrence G. Decamora III, scjp

This UML will have the following Java Class equivalent: public class { public public public } Person String name; int age; void showDetails() {...}

How to create an object? Let us create two objects. Person p1 = new Person(); Person p2 = new Person(); This means that p1 and p2 are reference variables that handles two different objects. More on reference variables on the next chapter. Since you have two objects now, it means that each object will have its own copy of name, and age attributes as well as the showDetails() method. If you want to access a member (a member is another name for both attributes and methods), you can use the dot (.) notation. For example, you would like to assign the name for the p1 and p2 objects respectively: p1.name = Lawrence; p2.name = Jeremy; Now, lets assign their respective ages: p1.age = 30; p2.age = 27; What we've done so far is to assign values to the attributes of p1 and p2. Now lets print their values: System.out.println(p1.name + at age + p1.age); System.out.println(p2.name + at age + p2.age); This will give us an output of: Lawrence at age 30 Jeremy at age 27 Encapsulation AKA Data Hiding What's the problem with the this class declaration? Person + name : String + age : int + showDetails() : void What if we do this?

Page 2 of 10

Prepared by: Lawrence G. Decamora III, scjp

10 11 12 13 14

p1.name = Lawrence; p2.name = Jeremy; p1.age = 30; p2.age = -5;

Will there be any programmatic problem? Will the compiler have a problem with this? This one will compile and run. The compiler should not have any problems on line 14 right? But we should have a problem with this. Java is said to be an object oriented programming language, that means it has the capability to mimic the behavior of real life objects. In this scenario, a real person cannot have a negative value for the age. In our real world, a person's age must be greater than or equal to zero. So, how are we going to solve this? This is where encapsulation comes in. Encapsulation is an object oriented feature that hides or protects data from direct access. So instead of declaring all attributes as public, we can declare them as private to disable the accessibility of the attributes to other classes directly. Person - name : String - age : int + showDetails() : void Now, the name and the age attributes are declared as private, this means these attributes can only be accessed within the class Person and cannot be accessed outside of this class including the TestPerson class. So if by declaring the name and age attributes as private, how are we supposed to assign and retrieve values to them? By providing a pair of setters and getters. Setters and getters are conventions used to create JavaBeans, it is now possible to assign values to the name and age attributes and as we assign values to them we can also provide verification checks as well. Java Beans is just a POJO (Plain Old Java Object) it is a conventional term for a well encapsulated object. Java Beans are not the same as Enterprise Java Beans (EJB), EJBs are the business component of a Java EE Application, it is also out of the scope of our topic as well. Here is an example of a Java Bean. Person - name : String - age : int // setters + setName(String n): void + setAge(int a): void // getters + getName() : String + getAge() : int + showDetails() : void
Page 3 of 10 Prepared by: Lawrence G. Decamora III, scjp

Translated into a Java Code, it will look like this: 1 // Person.java 2 public class Person 3 { 4 private String name; 5 private int age; 6 7 // setters 8 public void setName(String n) 9 { 10 name = n; 11 } 12 public void setAge(int a) 13 { 14 if (a >= 0) 15 age = a; 16 else 17 age = 0; 18 } 19 20 // getters 21 public String getName() 22 { 23 return name; 24 } 25 public String getAge() 26 { 27 return age; 28 } 29 30 public void showDetails() {...} 31 } 32 In this revised Person class, you will notice that even if you try to assign a negative value for the person's age, it will not be possible. It will first test the passed value, test it, then assign. Let's now see out revised TestPerson class as well. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // TestPerson.java public class TestPerson { public static void main(String args[]) { Person p1 = new Person(); Person p2 = new Person(); // assign names p1.setName("Lawrence"); p2.setName("Jeremy"); // assign age p1.setAge(30); p2.setAge(-5);

// value assigned will be changed.

System.out.println(p1.getName()+ " is " + p1.getAge()+ " years old.");


Prepared by: Lawrence G. Decamora III, scjp

Page 4 of 10

18 19 20 21 } }

System.out.println(p2.getName()+ " is " + p2.getAge()+ " years old.");

Once compiled and runned, it will have this output: Lawrence at age 30 Jeremy at age 0 The Constructor The constructor is a method like construct that has the same name as your class name but does not have any return type, not even void. Here's an example: 10 public class Person 11 { 12 public Person (String n, int a) 13 { 14 name = n; 15 age = a; 16 } 17 } Lines 12 to 16 is your constructor body. And to use them to create a person object you use them this way. Person p1 = new Person(Lawrence, 20); Person p2 = new Person(Jeremy, 18); The Default Constructor's [Golden] Rule: There is always atleast one constructor for each class, if the writer does not provide a constructor, Java will provide the default, no-argument, empty body constructor. For example: public class MyClass { // nothing here } Does this class contains a constructor? The answer is YES. That is because of the constructor's golden rule This is the reason we can instantiate an object from this class. The given class will actually look like this: public class MyClass { public MyClass() { // nothing here } }
Page 5 of 10

// this is the default constructor

Prepared by: Lawrence G. Decamora III, scjp

The default constructor is provided so that even if the writer does not provide a constructor we can still create an object from a class such as this one: MyClass mc = new MyClass(); Creating an object from this class is actually a call from the default constructor provided by Java. The Java Source File Layout: Just remember PIC, which stands for PackageImport---Classes. All parts of the Java Source file are optional. You can have the following number of statements per part: package import classes Packages Packages in Java refers to subdirectories. A package may contain classes or sub-packages. Take this diagram as an example. We have MyProj as a package and within MyProj, we have three sub packages namely: subA, subB and test. And within subA, we have subAA as a sub-package. A package may also contains classes inside it. The package subA contains A.class, subAA contains AA.class, package subB contains B.class and package test contains TestMe.class that serves as our test class. --> 0 or 1 statement --> 0 to many --> 0 to many

MyProj subA subAA A test AA TestMe subB B

Page 6 of 10

Prepared by: Lawrence G. Decamora III, scjp

In using packages, we also need to be aware of the following rules. 1. The basic syntax of a package is this: package <top_level_pkg_name>[.<sub_pkg_name>]*; 2. Example: package subA.subAA; 3. The package declaration can only be placed at the beginning of a Java Source File 4. Only one (1) package declaration per source file is allowed. 5. In the absence of the package statement, the generated class file will be placed on the default package (the present working directory). 6. Package statements must be separated by dots (.) to make subdirectory representation platform independent. Import Statements Import statements are used to tell the compiler where to find the needed classes that your application will use. There are two (2) default packages that does not need any import statements. 1. the present working directory and; 2. the java.lang.*; package. Classes inside the above mentioned packages do not require any import statement declarations. However, classes found on other packages must be declared using an import statement. Here's an example: 1 import java.util.ArrayList; 2 import java.io.*; 3 import subA.subAA.AA; Line 1 states that the ArrayList class can be inside the java.util package, while Line 2 states that all classes under java.io package can be used. The asterisk (*) signifies all classes. While line 3 states that this application is using the class AA which is located under subA.subAA package. Putting it all together, here's an example. This is the TestMe.java source file. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package test; import subA.*; import subA.subAA.AA; //import subB.B; public class TestMe { public static void main(String args[]) { A a = new A(); AA aa = new AA(); subB.B b = new subB.B(); // fully-qualified name a.printMe(); aa.printMe(); b.printMe();

} }

Page 7 of 10

Prepared by: Lawrence G. Decamora III, scjp

Line 1 states that once this source file compiles, the TestMe.class that will be generated will be placed under the test subdirectory. Lines 3 and 4 states that classes A.java and AA.java are needed inside this application and are located under the declared packages. Line 5 is commented out. If this is the case, you need to use the fully qualified name in line 13 so that you can still use the B.java source file. Here is a preview of the developer's subdirectory structure: \MyProj \src \subA A.java \subAA AA.java \subB B.java \test TestMe.java \classes \subA A.class \subAA AA.class \subB B.class \test TestMe.class Compiling the test class will also compile the rest of the *.java files. To compile them use the following command: MyProj\src> javac -d ..\classes test\TestMe.java
Page 8 of 10 Prepared by: Lawrence G. Decamora III, scjp

If this command is successful, the generated class files should be under the classes folder. To run the sample application, you can type in: MyProj\src> java -cp ..\classes test.TestMe The JAR (Java Archive) File A complex application is normally composed of a set of class files and not just one class file. When these class files needs to be delivered to your client, we need to put them inside one file called the JAR File or the Java Archive File. This Jar file represents a group of classes that works together. There are two (2) ways on how to create a Jar File. 1. without a manifest file to create: jar cvf <JarFile.jar> <Files> ie: jar cvf MyJar1.jar * to run: java -cp <JarFile.jar> <fullyQualifiedName> ie: java -cp MyJar1.jar test.TestMe 2. with a manifest file, also known as the executable Jar File. to create: jar cvfm <JarFile.jar> <manifestFile> <Files> ie: jar cvfm MyJar2.jar manif.txt * to run: java -jar <JarFile.jar> ie: java -jar MyJar2.jar A manifest file looks like this: Main-Class: test.TestMe <ENTERKEY> Be sure to add a next line character after this line so that during runtime, the Java Virtual Machine can read this line input. In the absent of the extra next line character JVM will treat this as an invalid manifest file. Java API Documentation As what was discussed on the previous chapter, the Java Runtime Environment (JRE) is composed to two main components: 1. the Java Virtual Machine (JVM) and the; 2. Application Program Interface (API) To know the classes inside your API, we could download the API documentation on Sun's website or you can access the API documentation on-line via the URL:

Page 9 of 10

Prepared by: Lawrence G. Decamora III, scjp

http://java.sun.com/javase/version/docs/api/index.html example: http://java.sun.com/javase/6/docs/api/index.html The Java API is composed of three (3) parts, the upper left part are the Java Packages, the lower left part are the list of Java Classes per package and the center part is the write up for the Java Classes. Try to click on one of the classes, say the String class, and read on the list of attributes, constructors and methods that the String class contains.

Page 10 of 10

Prepared by: Lawrence G. Decamora III, scjp

Das könnte Ihnen auch gefallen