12/10/2022
JAVA PROGRAMMING
Week 3: Classes, Objects and
Methods
Lecturer: NGUYỄN Thị Minh Tuyền
Plan 2
1. Class fundamentals
2. Methods
3. Constructors
4. The new operator revisited
5. Garbage collection
6. The this keyword
Java Programming
1
12/10/2022
Plan 3
1. Class fundamentals
2. Methods
3. Constructors
4. The new operator revisited
5. Garbage collection
6. The this keyword
Java Programming
Class: General Form 4
1. class classname {
2. // declare instance variables type var1;
3. type var1;
4. // ...
5. type varN;
6. // declare methods
7. type method1(parameters) {
8. // body of method
9. }
10. // ...
11. type methodN(parameters) {
12. // body of method
13. }
14. }
Java Programming
2
12/10/2022
Example: Defining a Class 5
1. class Vehicle {
2. int passengers; // number of passengers
3. int fuelcap; // fuel capacity in gallons
4. int mpg; // fuel consumption in miles per gallon
5. }
Java Programming
6
1. public class VehicleDemo {
2. public static void main(String[] args) {
3. Vehicle minivan = new Vehicle();
4. int range;
5. // assign values to fields in minivan
6. minivan.passengers = 7;
7. minivan.fuelcap = 16; minivan.mpg = 21;
8. // compute the range assuming a full tank of gas
9. range = minivan.fuelcap * minivan.mpg;
10. System.out.println("Minivan can carry " +
11.
minivan.passengers +
12.
" with a range of " + range);
13.
}
14.
}
Java Programming
3
12/10/2022
1. ...
2. Vehicle minivan = new Vehicle();
7
3. Vehicle sportscar = new Vehicle();
4. int range1, range2;
5. // assign values to fields in minivan
6. minivan.passengers = 7;
7. minivan.fuelcap = 16; minivan.mpg = 21;
8. // assign values to fields in sportscar
9. sportscar.passengers = 2;
10. sportscar.fuelcap = 14; sportscar.mpg = 12;
11. // compute the range assuming a full tank of gas
12. range1 = minivan.fuelcap * minivan.mpg;
13. range2 = sportscar.fuelcap * sportscar.mpg;
14. System.out.println("Minivan can carry " + minivan.passengers
15. + " with a range of " + range1);
16. System.out.println("Sportscar can carry " + sportscar.passengers
17. + " with a range of " + range2);
Java Programming
How objects are created 8
Vehicle minivan = new Vehicle();
• This declaration performs two functions
• declares a variable called minivan of the class type Vehicle.
• creates an instance of the object and assigns to minivan a
reference to that object. This is done by using the new operator.
• The statement can be rewritten:
Vehicle minivan; // declare reference to object
minivan = new Vehicle(); // allocate a Vehicle object
Java Programming
4
12/10/2022
Reference variables and
assignment 9
1. Vehicle car1 = new Vehicle();
2. Vehicle car2 = car1;
3. car1.mpg = 26;
4. System.out.println("Car 1: " + car1.mpg);
5. System.out.println("Car 2: " + car2.mpg);
Result:
Java Programming
10
1. Vehicle car1 = new Vehicle();
2. Vehicle car2 = car1;
3. Vehicle car3 = new Vehicle();
4. car2 = car3 ;
5. // now car2 and car3 refer to the same object
Java Programming
10
5
12/10/2022
Plan 11
1. Class fundamentals
2. Methods
3. Constructors
4. The new operator revisited
5. Garbage collection
6. The this keyword
Java Programming
11
Method 12
ret-type name(parameter-list) {
// body of method
}
• ret-type specifies the type of data returned by the
method.
• This can be any valid type, including class types that you create.
• If the method does not return a value, its return type must be void.
• The name of the method is specified by name.
• The parameter-list is a sequence of type and identifier pairs
separated by commas.
Java Programming
12
6
12/10/2022
Adding a Method to the Vehicle
Class 13
1. class Vehicle1 {
2. int passengers; // number of passengers
3. int fuelcap; // fuel capacity in gallons
4. int mpg; // fuel consumption in miles per gallon
5. // Display the range
6. void range() {
7. System.out.println("Range is " + fuelcap * mpg);
8. }
9. }
Java Programming
13
14
1. public class AddMethod {
2. public static void main(String[] args) {
3. Vehicle1 minivan = new Vehicle1();
4. Vehicle1 sportscar = new Vehicle1();
5. ...
6. System.out.print("Minivan can carry " +
7. minivan.passengers + ". ");
8. minivan.range();
9. System.out.print("Sportscar can carry " +
10. sportscar.passengers + ". ");
11. sportscar.range();
12. }
13. }
Java Programming
14
7
12/10/2022
Returning from a method 15
• In general, there are two conditions that cause a method
to return:
• when the method’s closing curly brace is encountered.
• when a return statement is executed.
• There are two forms of return
• return ; cause the immediate termination of a void method
• returning values.
void myMethod() {
for(int i = 0; i < 10; i++) {
if (i == 5) return; // stop at 5
System.out.println();
}
}
Java Programming
15
Returning a value 16
1. // Use a return value.
2. class Vehicle2 {
3. int passengers; // number of passengers
4. int fuelcap; // fuel capacity in gallons
5. int mpg; // fuel consumption in miles per gallon
6. // Display the range
7. int range() {
8. return fuelcap * mpg;
9. }
10. }
Java Programming
16
8
12/10/2022
1. public class RetMethod {
2. public static void main(String[] args) { 17
3. Vehicle2 minivan = new Vehicle2();
4. Vehicle2 sportscar = new Vehicle2();
5. int range1, range2;
6. ...
7. //get the ranges
8. range1 = minivan.range();
9. range2 = sportscar.range();
10. System.out.println("Minivan can carry " +
11. minivan.passengers + " with a range of " + range1);
12. System.out.println("Sportscar can carry " +
13. sportscar.passengers + " with a range of " +
14. range2);
15. }
16. }
Java Programming
17
Using parameters 18
• It is possible to pass one or more values to a method
when the method is called.
• A value passed to a method is called an argument.
• Inside the method, the variable that receives the
argument is called a parameter.
• Parameters are declared inside the parentheses that
follow the method’s name.
Java Programming
18
9
12/10/2022
19
1. class ChkNum{
2. // return true if x is even
3. boolean isEven(int x) {
4. if ((x%2) == 0) return true;
5. else return false;
6. }
7. }
8. public class ParamDemo {
9. public static void main(String[] args) {
10. ChkNum e = new ChkNum();
11. if(e.isEven(10)) System.out.println("10 is even.");
12. if(e.isEven(9)) System.out.println("9 is even.");
13. if(e.isEven(8)) System.out.println("8 is even.");
14. }
15. }
Java Programming
19
20
1. class Factor{
2. boolean isFactor(int a, int b) {
3. if((b%a) == 0) return true;
4. return false;
5. }
6. }
7. public class IsFact {
8. public static void main(String[] args) {
9. Factor x = new Factor();
10. if(x.isFactor(2, 20)) System.out.println(
11. "2 is factor");
12. if(x.isFactor(3, 20)) System.out.println(
13. "This won't be displayed");
14. }
15. }
Java Programming
20
10
12/10/2022
Example: Adding a
Parameterized Method 21
1. class Vehicle3 {
2. int passengers; // number of passengers
3. int fuelcap; // fuel capacity in gallons
4. int mpg; // fuel consumption in miles per gallon
5. // Return the range
6. int getRange() {
7. return mpg * fuelcap;
8. }
9. // Compute fuel needed for a given distance.
10. double getFuelNeeded(int miles) {
11. return (double) miles / mpg;
12. }
13. }
Java Programming
21
1. public class CompFuel {
2.
3.
public static void main(String[] args) { 22
Vehicle3 minivan = new Vehicle3();
4.
Vehicle3 sportscar = new Vehicle3();
5.
double gallons;
6.
7. int dist = 252;
8. ...
9. gallons = minivan.getFuelNeeded(dist);
10. System.out.println("To go " + dist +
11. " miles minivan needs " + gallons +
12.
" gallons of fuels.");
13. gallons = sportscar.getFuelNeeded(dist);
14.
System.out.println("To go " + dist +
15.
" miles sportscar needs " + gallons +
16.
" gallons of fuels.");
17.
}
}
Java Programming
22
11
12/10/2022
Exercise: Improve Help example 23
1. class Help{
2. void helpOn(int what) {
3. // Display the help information based on a user's
choice
4.
}
5.
void showMenu() {
6.
// Show menu option
7.
}
8.
boolean isValid(int choice) {
9. // Check for a valid response
10. return true;
11. }
12. }
Java Programming
23
24
1. public class HelpClassDemo {
2. public static void main(String args[])
3. throws java.io.IOException{
4. // Create an instance of Help class
5. /* Invoke all the methods in that instance in order to:
6. * - Display a menu,
7. * - Input the user’s choice, check for a valid
8. * response, and display information about the item
9. * selected.
10. * The program also loops until the letter q is pressed.
11. */
12. }
13. }
Java Programming
24
12
12/10/2022
Plan 25
1. Class fundamentals
2. Methods
3. Constructors
4. The new operator revisited
5. Garbage collection
6. The this keyword
Java Programming
25
Constructor 26
• A constructor initializes an object when it is created.
• It has the same name as its class and is syntactically
similar to a method.
• Constructors have no explicit return type.
• Use a constructor to give initial values to the instance variables
defined by the class, or to perform any other startup procedures
required to create a fully formed object.
• All classes have constructors, whether you define one or
not, because Java automatically provides a default
constructor.
• Once you define your own constructor, the default
constructor is no longer used.
Java Programming
26
13
12/10/2022
Example 27
1. class MyClass{
2. int x;
3. MyClass(){
4. x = 10;
5. }
6. }
7. public class ConsDemo {
8. public static void main(String[] args) {
9. MyClass t1 = new MyClass();
10. MyClass t2 = new MyClass();
11. System.out.println(t1.x + " " + t2.x);
12. }
13. }
Java Programming
27
Parameterized constructors 28
• Most often you will need a constructor that accepts one or
more parameters.
• Parameters are added to a constructor in the same way
that they are added to a method: just declare them inside
the parentheses after the constructor’s name.
• Example:
// A parameterized constructor
MyClass(int i){
x = i;
}
....
MyClass t3 = new MyClass(10);
Java Programming
28
14
12/10/2022
Example: Adding a constructor to
the vehicle class 29
1. //This is a constructor for Vehicle
2. Vehicle4(int p, int f, int m){
3. passengers = p;
4. fuelcap = f;
5. mpg = m;
6. }
7. ....
8. Vehicle4 minivan = new Vehicle4(7, 16, 21);
9. Vehicle4 sportscar = new Vehicle4(2, 14, 12);
Java Programming
29
The new operator revisited 30
classvar = new classname(arglist);
• classvar is a variable of the class type being created.
• classname is the name of the class that is being
instantiated.
Java Programming
30
15
12/10/2022
Garbage collection [1] 31
• Objects are dynamically allocated from a pool of free
memory by using the new operator.
• Memory is not infinite, and the free memory can be
exhausted.
• It is possible for new to fail because there is insufficient free
memory to create the desired object.
àFor this reason, a key component of any dynamic allocation
scheme is the recovery of free memory from unused objects,
making that memory available for subsequent reallocation.
à garbage collection
Java Programming
31
Garbage collection [2] 32
• Java’s garbage collection system reclaims objects
automatically – occurring transparently, behind the
scenes, without any programmer intervention.
• It works like this:
• When no references to an object exist à that object is assumed
to be no longer needed à the memory occupied by the object is
released.
• This recycled memory can then be used for a subsequent
allocation.
Java Programming
32
16
12/10/2022
The this keyword 33
• When a method is called, it is automatically passed an
implicit argument that is a reference to the invoking object
àThis reference is called this.
• However, this has some important uses.
• Java syntax permits the name of a parameter or a local
variable to be the same as the name of an instance
variable.
• When this happens, the local name hides the instance variable.
• You can gain access to the hidden instance variable by referring
to it through this.
Java Programming
33
1. class Pwr2{
2.
3.
double base;
int e;
34
4. double val;
5. Pwr2(double base, int exp){
6. this.base = base;
7. this.e = exp;
8. this.val = 1;
9. if(exp == 0) return;
10. for(; exp > 0; exp--) this.val = this.val * base;
11. }
12. double getPwr() {
13. return this.val;
14. }
15. }
Java Programming
34
17
12/10/2022
35
QUESTION ?
Java Programming
35
18