Anda di halaman 1dari 15

Modules: Print Module

https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
Send to Printer | Close Window

Lesson 3: OO: Classes, objects and methods
OO: Classes, objects and methods
OO: Classes, objects and methods
Objectives
In this lesson, you will learn how to:
For the Android environment
Create radiobuttons and radiocontrol widgets
For Java coding

Recognize the correct general form of a class
Create an object of a class
Describe object references
Create methods that compile with no errors
Return a value from a method
Use parameters in a method
Add a constructor to a class
Apply the new operator
Describe garbage collection and finalizers
Apply the this reference
Purpose
Class templates are the foundation of the J ava language.
Understanding how to create a class with various methods will be essential to becoming a good J ava programmer.
Knowing how to instantiate an object and compare it to other objects is critical to learning to use and work with J ava data types.


RadioButton and RadioGroup controls
RadioButton and RadioGroup controls
RadioButton and RadioGroup controls
RadioButton controls are used to select or deselect an option.
When a radionbutton is added to a screen, the controls are arranged vertically. You can change it by setting the orientation property horisontal.
Each radiobutton control has a label defined by the Text property and a Checked property that is set to either true or false..
Radiobuttons are used together in a RadioGroup.
When checking one radio button in a group, the other radio buttons in the same group is dechecked. You can also preset a default selection to
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
be true.
Create a RadioButton Group in Android
Create an Android application (MENU). In this menu the user can choose between 3 differents starters, 3 different main courses and 4 different
sweets. The items on the menu has different prices. The total of the choices must be displayed at the bottom.
Specs:
- Android Application
- One screen
- Two different RadioButton Groups
Group 1 - Listing 3 different starters
Group 2 - Listing 3 different main courses
- Calc Button
- Field where the total is displayed.

Create your Android application.
Create a new Android application.
On the act i vi t y_mai n layout, add the following widgets:
A top message, such as: Select your items from our menu.
Then, add a RadioGroup to the screen:

Click on the first item (radio button), provide it with a proper id and Text. E.g. id =radSnails. Text =Snails.
Do the same with all the other radio buttons.
Below is an example:
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]

Now we need to provide the coding in the Calc Button.
Open the Mai nAct i vi t y. j ava class.
We will use the I F statement and the radiobutton.i sChecked method to determine whether a button was checked. If it was checked the price of
the item is added to the Tot al .
Below is the code that you can use to program the radio buttons.
/ / Li nk t he r adi o but t ons f or st ar t er s t o t he code
f i nal Radi oBut t on r RadSnai l s = ( Radi oBut t on) f i ndVi ewByI d( R. i d. r adSnai l s) ;
f i nal Radi oBut t on r RadChi ckLi ver s = ( Radi oBut t on) f i ndVi ewByI d( R. i d. r adChi ckenLi ver s) ;
f i nal Radi oBut t on r RadBr eadRol l s = ( Radi oBut t on) f i ndVi ewByI d( R. i d. r adBr eadRol l s) ;

/ / Li nk t he r adi o but t ons f or t he mai n cour ses t o t he code
f i nal Radi oBut t on r RadRi bs = ( Radi oBut t on) f i ndVi ewByI d( R. i d. r adRi bs) ;
f i nal Radi oBut t on r RadChi ck = ( Radi oBut t on) f i ndVi ewByI d( R. i d. r adFr i edChi ck) ;
f i nal Radi oBut t on r RadVeg = ( Radi oBut t on) f i ndVi ewByI d( R. i d. r adVegPl at t er ) ;


f i nal Text Vi ew f Cal c = ( Text Vi ew) f i ndVi ewByI d( R. i d. t xt Tot al ) ;
/ / Var i abl es t hat I wi l l use i n t he pr ogr am- pr i ces of t he i t ems

f i nal doubl e SNAI LS = 50;
f i nal doubl e CHI CKLI VER = 45. 50;
f i nal doubl e BREADROLLS = 35. 50;
f i nal doubl e RI BS = 89. 90;
f i nal doubl e CHI CKEN = 114. 90;
f i nal doubl e VEGPLATTER = 95. 90;


But t on but Cal c = ( But t on) f i ndVi ewByI d( R. i d. bt nCal c) ;
but Cal c. set OnCl i ckLi st ener ( new OnCl i ckLi st ener ( ) {
publ i c voi d onCl i ck( Vi ew v) {
/ / Thi s i s wher e your code wi l l go
/ / var i abl es I wi l l be usi nG
doubl e Tot al = 0; / / Keepi ng t r ack of t he t ot al bi l l
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
St r i ng sTot al ;

/ / check whi ch r adi o but t on was pr essed f or t he st ar t er s

i f ( r RadSnai l s. i sChecked( ) )
{Tot al = Tot al + SNAI LS; }
el se i f ( r RadChi ckLi ver s. i sChecked( ) )
{Tot al = Tot al + CHI CKLI VER; }
el se i f ( r RadBr eadRol l s. i sChecked( ) )
{Tot al = Tot al + BREADROLLS; }

/ / check whi ch r adi o but t on was pr essed f or t he mai n cour se

i f ( r RadRi bs. i sChecked( ) )
{Tot al = Tot al + RI BS; }
el se i f ( r RadChi ck. i sChecked( ) )
{Tot al = Tot al + CHI CKEN; }
el se i f ( r RadVeg. i sChecked( ) )
{Tot al = Tot al + VEGPLATTER; }
/ / pr i nt t he t ot al
sTot al = Doubl e. t oSt r i ng( Tot al ) ;
f Cal c. set Text ( " R " + sTot al ) ;
}/ / end of onCl i ck
}) ;
SAVE it, compile it, remove all errors and RUN it.
If you really struggle then download my code from myUNISA.

Classes and objects: the basics
Classes and objects: the basics
Understanding the basics of classes
Up to now we have been using the Classes provided by Eclipse and J ava, such as MainActivity. Then we created one or two of our own classes,
such as For Loop. j ava and I f AndSwi t ch. j ava in the Loop application.
But we haven't really sat down and discussed as to what classes are. What are methods? How do we create them, when and where do we use it.
Object oriented programming languages, such as J ava, is ALL about creating classes and methods.
What is a class? (Blueprint)
A class is a "blueprint". In this class you will have a number of methods (some non-oo programming languages call it procedures or functions). In
this class you are going to describe (by coding) exactly what this class can do.
E.g. a may create a class called Student. And in this class I will specify that to be a student, you must have a name, surname, id number, telephone
number. Furthermore you need to be enrolled for a specific course, e.g. Diploma in IT, or Diploma in Engineering.

What is an object?
Well an object is an instantiation of the class! That is there is a class called Student and there may be zero, one or many students (objects), we can
call them stud1, stud2, stud3, .... etc. to distinguish between them. But all of these students will be objects of Student. And since they are objects of
Student they will all have the same methods to their use.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
J ust as for Student you could create a class called Course.
Course will then be the blue print for all future courses.
What is a method?
A method is a piece of coding within the class that does something. For instance, after a new student (object) is created I would like to have the
surname, name and course be displayed.
Variables
To do this coding in the class we will work with (just as before with variables).
There are mainly three types of variables, namely

Variables defined inside methods, constructors or blocks are called local
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
Local
variables

variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed. These variables cannot
be accessed to the any other class or program.

Instance
variables

Instance variables are variables within a class but outside any method. These
variables are instantiated when the class is loaded. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.

Class
variable
Class variables are variables declared with in a
class, outside any method, with the static
keyword. These variables can be accessed by
other classes or programs.
A class can have any number of methods to access the value of various kinds of methods.
Constructors
Constructors is another terminology that you will hear often when speaking OO-language!
Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked.
The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
You will understand this when we go into the coding.
But what it basiclly does is:
When you call a class say Student, you are creating a new instance thereof.
Now, in some instances you may have all the information available for the student that you would like to create, name, surname, telephone number,
etc. Then there will be constructor that will accept ALL the information (it must be coded this way!).
Then in other instances it may be that you don't have the course details of a new student, then you will have a constructor that will accept only the
minimum information, such as name and surname (it must be coded this way!)
We will come back to this (overloading) again in one of the later lessons and discuss it in more detail.


Activity: create the class Student and objects thereof
Activity: create the class Student and objects thereof
Activity
Creating our own class: Student and create objects thereof
We need to create a class called : Student.
Specs for the class: Student
- Three constructors:
First constructor must not accept any information
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
Second constructor must accept the following details to create a new student:
name, surname and email.
Third constructor must accept all the details to create a new student:
name, surname, email, RSA ID number, address and course

- Two methods:
First method get St udI nf o( ) must display the name +surname and email.
Second method get Bday( ) . This method will use the ID number and return DD Month YYYY.

Open Eclipse and create a new Android Application.
Save it as MySt udent s.
Create one TextView widget one button on the main screen. Put it to the bottom of the screen. We will the different fields where the user can enter
the student information, name, etc.
Create the usual coding to link the Text Vi ewand but t on wi dget s to the coding.
We will do the rest of the coding later.

Create the class Student
First we need to create the class. You have some previous experience in this when we created a class for the additional screens.
Expand the sr c, on Mai nAct i vi t y. j ava, click right, select Newand then Cl ass.
Call it St udent (with a capital S since we are creating a class) . Verify that
publ i c st at i c voi d mai n is deselected and save your new class.
If it is not open, double click on St udent . j ava to open the new class. Note that there is no significant coding in this class at the moment.
Step 1: Create the first constructor that is "empty" (accepts to parameters)
publ i c cl ass St udent {
//the first constructor without any variables
public Student()
{ } //the empty constructor

}
Step 2: Create the second constructor that accepts the name, sur name and emai l addr ess.
To do this, we need to create variables where this information can be stored (viz name, sur name and emai l ). These will be instance variables.
They will be inside the class but not within any method.
Furthermore, we need to indicate in the constructor the same parameters, namely name, surname and email address. These parameters will be
used in the main program when the class is called to create a new instance.
Below is the coding for the second constructor.
publ i c cl ass St udent {

/ / t he f i r st const r uct or wi t hout any var i abl es
publ i c St udent ( )
{} / / t he empt y const r uct or

Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
//instance variables that I will use in the class that
//corresponds to the parameters for the second constructor

String studName, studSurname, studEmail;

//the second constructor with 3 variables, name, surname and email
public Student(String name, String surname, String email){
//linking the 3 variables to the instance variables using this.
this.studName = name;
this.studSurname = surname;
this.studEmail = email;

}

}

Step 3: Create the third constructor that accepts the name, surname, RSA ID number, telephone number, address, email and course.
J ust as before we need to add to our instance the variables, RSA ID number, telephone number, address and course.
In our constructor we need to add all of these fields.
publ i c cl ass St udent {

/ / t he f i r st const r uct or wi t hout any var i abl es
publ i c St udent ( ) {}

/ / i nst ance var i abl es t hat I wi l l use i n t he cl ass
St r i ng st udName, st udSur name, st udEmai l ;
String studID, studTel, studAddress, studCourse;

/ / t he second const r uct or wi t h 3 var i abl es, name, sur name and emai l
publ i c St udent ( St r i ng name, St r i ng sur name, St r i ng emai l ) {

/ / l i nki ng t he 3 var i abl es t o t he i nst ance var i abl es usi ng t hi s.
t hi s. st udName = name;
t hi s. st udSur name = sur name;
t hi s. st udEmai l = emai l ;

}

//the third constructor with all the variables
public Student(String name, String surname, String email,
String id, String address, String course)
{

//linking the variables to the instance variables using this.
this.studName = name;
this.studSurname = surname;
this.studEmail = email;
this.studID = id;
this.studAddress = address;
this.studCourse = course;
}

}
Initial testing to see if the class Student is created correctly
Go back to Mai nAct i vi t y. j ava.
If you haven't done it yet, create the code for the button and enter the following code to create three new instances (objects) of the class St udent
(inside the code for the button)
Note the format: ClassName obj ect Name = new ClassName( variables for the constructors) ;
e.g. St udent st ud1 = new St udent ( " Len" , " Mki ze" , " l mki ze@gmai l . com" ) ;
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
Below is the code (inside the button)
/ / code t o cr eat e t he but t on
But t on but Show = ( But t on) f i ndVi ewByI d( R. i d. bt nShow) ;
but Show. set OnCl i ckLi st ener ( new OnCl i ckLi st ener ( ) {
publ i c voi d onCl i ck( Vi ew v) {
/ / Thi s i s wher e your code wi l l go
/ /create a new Student1 with no know values
Student stud1 = new Student();
//create a new Student2 with 3 values, name, surname and email
Student stud2 = new Student("John","Nel","jnel@gmail.com");
//create a new Student3 with all the values, name, surname, email, id, address,
//course
Student stud3 = new Student("Peter","Seopa","pseopa@gmail.com","9111030129089",
"PO Box123, Pretoria","98806");
}/ / end of onCl i ck
}) ;

Save, compile, remove all errors and run the code.
At this stage only the activity_main.xml main screen will appear with the button visible, but clicking on it will have no effect since we haven't really
coded any methods or actions.
When you click on the but t on then the three objects st ud1, st ud2 and st ud3 are created (although you can't "see" it).
If you struggle, download from Additional Resources a copy of my code (The copy contains the coding for this page as well as the next pages)

Activity: add methods to class Student
Activity: add methods to class Student
Activity

Activity
Add methods to the class Student
We are now ready to add methods to our class St udent .
Remember that methods (procedures or functions in non-OO programming languages) DO something.
A class can have many methods.
Some methods will be visible (public) to the "outside" program, in our case Mai nAct i vi t y. j ava and other methods will not be visible
(private) to other methods and programs. It all depends on the purpose of the method.

Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
The syntax for methods:
There are two types of methods:
1) a method that returns a value:
publ i c | pr i vat e r et ur n t ype Name of Met hod ( par amet er s f r omcal l i ng pr ogr am)
{ the code;
return something of the same type;}
Exampl es
publ i c i nt det Sum( i nt val 1, i nt val 2) {
/ / t hi s met hod i s vi si bl e t o ot her pr ogr ams and cl asses
i nt answer ;
answer = v1 + v2;
return answer ;
}
pr i vat e St r i ng showI nf o( St r i ng i d) {
/ / t hi s met hod i s onl y vi si bl e t o t he cl ass
return i d. subst r i ng( 1, 2) ;
}

2) a method that does not return a value.

publ i c | pr i vat e voi d Name of Met hod ( par amet er s f r omcal l i ng pr ogr am)
{ the coding ;}

Examples:
pr i vat e voi d cr eat ePasswor d( ) {
St r i ng passwor d = t hi s. st udName. subst r i ng( 1, 3) +
t hi s. st udSur name. subst r i ng( 1, 4) ;


}
Read more on Classes and Methods: http://docs.oracle.com/javase/tutorial/java/javaOO/index.html


Add our own methods to the class Student
We are now ready to add the get St udI nf o( ) and method to the St udent class.
Open the St udent . j ava class.
You will enter the code for the methods at the end of the Class, just before the last curly bracket }.
The purpose of the get St udI nf o( ) method is to return to the main program (Mai nAct i vi t y. j ava) the name, surname and course information
as one string, e.g. J an Brand 98806.
Specs:
- Method for the class Student: get St udI nf o( )
- Must return a String to the calling program.
- Use the Instance variables (this.name, this.surname and this.course) from the class Student.

Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
Below is the code to create the method getStudInfo()
public String getStudInfo() {
// my code
String studInfo;
studInfo = studName + " " + studSurname + " " + studCourse;
return studInfo;

}
Notice that the method is declared as public since we need to return something to the calling program.
And since we are returning a string (text) the return type is String.
Save it, compile and test for errors. Again, nothing will happen. We have created the method, but we still need to use it in our main (calling)
program.

Use this method in the MainActivity.java program.
Go back to Mai nAct i vi t y. j ava.
Enter the following code after the code where you've initiated the object st ud3.
//call the method getStudInfo() and allocated the answer to displayStudent
String displayStudInfo = stud3.getStudInfo();
//display the info in the TextView field.

fShow.setText(displayStudInfo);

Save, Compile, test and decode.
Run the application.
This time, when you click on the button you should see the information displayed in the Text Vi ewfield, e.g. Peter Seopa 98806.

Add EditText fields to the screen and use the information from the EditText fields to initiate the objects stud1, stud2 and stud3.
Below is an output of the screen layout. First try to do the coding on your own and if you really struggle download the code from myUNISA.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
Notice that for this exercise I've included the complete coding in ZIP file (all the classes, XML, bin, etc).

Understanding Garbage collection
Understanding Garbage collection
Understanding Garbage Collection
Memory management is one of the most difficult things to master as a computer programmer.
Luckily, J ava has a special functionality called garbage collection.
Cleans up unused memory
Prevents memory leaks, free errors, and dangling pointers.
Consider the following J ava code:
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
St udent st ud1 = new St udent ( " J ohn" , " Nel " , " j nel @gmai l . com" ) ;
St udent st ud2 = new St udent ( " Pet er " , " Seopa" , " seopa@gmai l . com" ) ;
What will happen (in cache memory) when the programmer code:
st ud1 = st ud2;
When executed, st ud1 = st ud2;
takes the pointer st ud2 and suddenly points it at st ud1.
This effectively renders the original object that st ud2 was pointing at useless but it still there in cache memor.
Garbage collection takes care of it by removing it from memory.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]

Finalizers
A finalizer is code that is called by the garbage collector when it determines no more references to the object exist.
All objects inherit afinalize() method from j ava. l ang. Obj ect .
This method takes no parameters and is written to perform no action when called.
Overriding this method in classes allows you to modify what happens before garbage collection, such as notifying the user about the garbage
collection that is about to occur, or cleaning up non-J ava resources such as closing a file.
Below is an example of the f i nal i ze( ) method overridden in a class.
It closes all associated files and notifies the user that the finalization occurs.
pr ot ect ed voi d f i nal i ze( ) {
t r y{
cl ose( ) ; / / cl ose al l f i l es
}
f i nal l y{
St r i ng message = " Fi nal i zat i on has occur ed" ;
}
}

Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144342[29/08/2014 19:04:14]
Reflection
Reflection
Reflection
Lesson 3: Summary
Now it is your turn ...
In the blogger add a blog entry. Label it Lesson 3. In this blog, enter a short summary for yourself of everything that we've learned. Specifically those
components that you've battled with and how you solved it.
Remember to keep notes and updates in your little black book.


Click here

Anda mungkin juga menyukai