Download presentation
Presentation is loading. Please wait.
Published byΤρίτωνος Ηλιόπουλος Modified over 6 years ago
2
Classes (review): A Java program consists of classes.
Most classes contain both instance variables and instance methods. Any object created from a class will have its own copy of the class’s instance variables, object can call the class’s (public) instance methods.
3
Variables in Java The variables in java classes: Instance variables
local variables Parameter variables Class/Static variables
4
Instance variables (Review)
Declared in a class, but outside a method, constructor or any block. E.g. public class Employee{ private String name; . } Their values are unique to each instance/object of a class Created when an object is created and destroyed when the object is destroyed. Have default values.
5
Local Variables Declared in the body of a method:
public double giveChange() { double change = payment – purchase; purchase = 0; payment = 0; return change; } Only visible to the method in which it is declared; No default values assigned. I.e.You must initialize local variables: The compiler complains if you do not Scope/lifetime of local variable
6
Parameter Variables Declared in the header of a method: E.g.
public void enterPayment(double amount) Initialized with the call values/argument values Local and parameter variables belong to methods: When a method is called/executed, its local and parameter variables come to life When the method exits, they are removed immediately/lifetime ends
7
Example: Parameter variable lifetime
amount comes to life call enterPayment method 2 1 method body executes 3 amount life ends 5 4 method exits and return control to next statement in main
8
static/class Variables
Instance variables vs static variables: Instance variables: each object has its own distinct copies Sometimes, you want to have variables that are common to all objects. Solution: static variables Static/class variables belongs to the class, NOT to any object of the class. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
9
Example1 Static variable
Example: BankAccount class with static var:fee=10, instance method = updatefee(newFee) BankAccountWithUpdateFee.java private static double fee =10; public void monthlyFee() { //double fee = 10.0; this.withdraw(fee); } public static void updateFee(int newFee) fee = newFee; Static variable Static variable is loaded to memory before object creation
10
How to Access a static variable
Recap: All objects share a single copy of the static/class variable That variable is stored in a separate location, outside any objects Class variables are referenced by the class name itself. <ClassName>. <staticVariableName> E.g. (totalStudents should be public to this) Student. totalStudents This makes it clear that they are class variables.
11
Recap – Class Variables
created when its class or interface is loaded initialized to a default value. Life ends when its class is unloaded.
12
Programming Question Modify BankAccount class to incorporate an accountNumber instance variable (and a static variable lastAssignedNumber that help you initialize accountNumber). Implement a toString method that takes no parametrs and returns a string with the String representation of class(E.g. “Bank Account No:1 balance:1000.0”). Tester code is given in next slide A sample run
13
public class BankAccountTester
{ public static void main(String args[]) BankAccount acct1 = new BankAccount( ); BankAccount acct2 = new BankAccount( ); BankAccount acct3 = new BankAccount( ); System.out.println(acct1.toString()); System.out.println(acct2); System.out.println(acct3); }
14
Answer public class BankAccount { private double balance;
BankAccount.java public class BankAccount { private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount(double balance) this.balance = balance; lastAssignedNumber++; accountNumber = lastAssignedNumber; } public String toString() return "Bank Account No:"+accountNumber+" balance:"+balance;
15
Answer public class BankAccountTester {
BankAccountTester.java public class BankAccountTester { public static void main(String args[]) BankAccount acct1 = new BankAccount( ); BankAccount acct2 = new BankAccount( ); BankAccount acct3 = new BankAccount( ); System.out.println(acct1.toString()); System.out.println(acct2); System.out.println(acct3); }
16
static Variables and Methods
Figure 5 A static Variable and Instance Variables
17
static Constants static variables: static constants:
Should always be declared as private, This ensures that methods of other classes do not change their values static constants: May be either private or public public class BankAccount { public static final double OVERDRAFT_FEE = 29.95; . . . } Methods from any class can refer to the constant as BankAccount.OVERDRAFT_FEE Only public methods+variables+constants sow up in javadoc api
18
Question Name a static constant of the Math class.
19
Answer Name a static constant of the Math class.
Answer: Math.PI, Math.E Use DrJava interaction pane to print the two constant values
21
Methods in Java The methods in java classes: Instance methods
Class/static methods
22
Instance Methods (Review)
An instance method may access the instance variables in an object without changing them, or it may modify instance variables. If acct is a reference to BankAccount object: BankAccount acct = new BankAccount(); then the call acct.deposit( ); deposits $1000 into the Account object that acct represents.
23
Class/static Methods A class method—like all methods in Java—must belong to a class. Class methods do not require access to instance variables (has nothing to do with objects).
24
Question The following method computes the average of two numbers:
double average(double a, double b) Why should/should not it be defined as an instance method?
25
Answer The method needs no data/instance variable acess of any object. The only required input is the values argument. So it shoudn’t be declared as instance method.
26
You can’t declare a method static if it access/update instance variables of the same class
Instance variable x is accessed in method WRONG!!! Compiler error
27
Class Methods Modifier static indicates the method is a class method
Many classes in the Java API provide class methods, including : Math, System, and String.
28
Example: The Math Class
Some Math static methods: Math.abs Math.max Math.min Math.pow Math.round Math.sqrt
29
Modifier=static indicates the method is a class method
30
How to call a static/class method
Syntax to call a class method: ClassName.classmethodName([arguments]); E.g. Math.abs(-10);
31
Example: The Math Class
The Math class is not instantiable. You cannot create objects from Math class. How do you know? No constructors in API page and ALL methods in API page are class methods The Math class contains no instance variables and no instance methods. It’s just a repository for math functions (class methods) and math constants.
32
Programming Question Write a program EquationSolver.java to calculate and the two roots of the equation: Define a=1, b=-3, c=-4 Sample output:
33
Answer EquationSolver.java
public class EquationSolver { public static void main(String args[]) int a = 1, b =-3, c=-4; double root1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); double root2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); System.out.println("root1="+root1); System.out.println("root2="+root2); }
34
Question Is String class instantiable?
35
Answer Yes Notice you have constructors listed in API
String is an example of a class that contains both instance methods and class methods.
36
Class/static methods
37
Example: The String Class
Java’s String class contains several overloaded class methods named valueOf that convert different types of data to string form. E.g.: String intString = String.valueOf(607); String doubleString = String.valueOf(4.5); The value of intString will be "607" and the value of doubleString will be "4.5".
38
Instance method call Static/class method call
39
Writing Class Methods Writing a class method is similar to writing an instance method, except that the declaration of a class method must contain the keyword static. Parts of a class method declaration: Access modifier The word static Result type Method name Parameters Body
40
Declaring Class Methods
Syntax accessModifier static returnType methodName([arguments]) { //your code here } Example of a class method declaration:
41
Example Class Method public class MyMath { public static int calculateSum(int a, int b) return (a+b); }
43
Method Rules Static Methods: Instance Methods:
can access static members (static variables + static methods) defined in same class. same CANNOT access instance members (instance variables + instance methods) in the same class. can access instance members of the same instance.
44
Example
45
Programming Question Modify the BankAccount class to do following:
Add a static method getLastAssignedNumber that returns the total number of accounts. (Think about why this method should be static - its information is not related to any particular account.) Modify BankAccountTester class to call this method and print total accounts created (i.e. last assigned Bank Account No.). Sample run:
46
Answer BankAccount.java public class BankAccount {
private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount() { this(0.0); } public BankAccount(double initialBalance) { balance = initialBalance; lastAssignedNumber++; accountNumber = lastAssignedNumber; public static int getLastAssignedNumber() return lastAssignedNumber; public String toString() return "Bank Account No:"+accountNumber+" balance:"+balance;
47
Answer BankAccountTester.java public class BankAccountTester {
public static void main(String args[]) BankAccount acct1 = new BankAccount( ); BankAccount acct2 = new BankAccount( ); BankAccount acct3 = new BankAccount( ); System.out.println(acct1.toString()); System.out.println(acct2); System.out.println(acct3); System.out.println("Last Assigned Bank Account Number="+BankAccount.getLastAssignedNumber()); }
48
public class BankAccountTester
{ public static void main(String args[]) System.out.println("Last Assigned Bank Account Number="+BankAccount.getLastAssignedNumber()); BankAccount acct1 = new BankAccount( ); BankAccount acct2 = new BankAccount( ); BankAccount acct3 = new BankAccount( ); System.out.println(acct1.toString()); System.out.println(acct2); System.out.println(acct3); }
49
Organizing Related Classes into Packages
In Java, related classes are grouped into packages.
50
Packages Package: Set of related classes
Important packages in the Java library:
51
Organizing Related Classes into Packages
A special package: default package If you did not include any package statement at the top of your source file its classes are placed in the default package. Has no name No package statement
52
Organizing Related Classes into Packages
To put classes in a package, you must place a line package packageName; as the first instruction in the source file containing the classes. Package name Consists of one or more identifiers separated by periods. Usually all lower case
53
To put the Financial class into a package named com. horstmann
To put the Financial class into a package named com.horstmann.bigjava, the Financial.java file must start as follows: package com.horstmann.bigjava; public class Financial { . . . } java.io Java.util.logging james.util james.io;
54
Syntax 8.1 Package Specification
55
Example1 com.horstmann.bigjava.A javac -d . *.java
package com.horstmann.bigjava; public class A{ } package com.horstmann.bigjava; public class B{ } package com.horstmann.bigjava; public class C{ } package com.horstmann.bigjava; public class D{ } base Place .java file anywhere you want (base directory) A.java B.java C.java D.java javac -d . *.java (or javac -d . A.java B.java C.java D.java) Command line compilation command to create the package structure: base A.java B.java C.java D.java com horstmann Path MUST matches the package name bigjava A.class B.class com.horstmann.bigjava.A C.class D.class
56
Example2 javac -d . *.java Place .java file anywhere you want
package com.horstmann.bigjava.ch01; public class A{ } package com.horstmann.bigjava.ch01; public class B{ } package com.horstmann.bigjava; public class C{ } package com.horstmann.bigjava.ch02; public class D{ } Place .java file anywhere you want (base directory) base javac -d . *.java A.java B.java C.java D.java com horstmann bigjava C.class ch01 A.class B.class ch02 D.class
58
To use the package Add package to jar file list Create the jar file
In the terminal go to base directory and type: jar cvf cs160.jar com/horstmann/bigjava/*.class Add jar file to classpath:
59
Import and use it: This code does not need to be located in same base directory the cs160.jar was generated
60
Package Names Package names should be unique.
Use packages to avoid name clashes: java.util.Timer vs. javax.swing.Timer A good choice for package name: turn the domain name in reverse: com.horstmann.bigjava Or write your address backwards: edu.sjsu.cs.walters
61
Programming Question Create a package cs160:
Modify BankAccount.java to include the package statement: package csbsju.cs160; Compile files in a terminal window: javac -d . BankAccount.java This will automatically create the directory structure and place .class file in csbsju/cs160 directory. Use BankAccount class template (with a main) in next slide Test if classes work from Base directory: java csbsju.cs160.BankAccount
62
Use following template:
public class BankAccount { private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount(double balance) this.balance = balance; lastAssignedNumber++; accountNumber = lastAssignedNumber; } public String toString() return "Bank Account No:"+accountNumber+" balance:"+balance; public static void main(String args[]) BankAccount acct1 = new BankAccount( ); BankAccount acct2 = new BankAccount( ); BankAccount acct3 = new BankAccount( ); System.out.println(acct1.toString()); System.out.println(acct2); System.out.println(acct3);
63
Answer BankAccount.java package csbsju.cs160;
public class BankAccount{ private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount(double balance) { this.balance = balance; lastAssignedNumber++; accountNumber = lastAssignedNumber; } public String toString() { return "Bank Account No:"+accountNumber+" balance:"+balance; public static void main(String args[]) { BankAccount acct1 = new BankAccount( ); BankAccount acct2 = new BankAccount( ); BankAccount acct3 = new BankAccount( ); System.out.println(acct1.toString()); System.out.println(acct2); System.out.println(acct3);
65
Answer Testing
66
Create a package Add package to jar file list Create the jar file
In the terminal go to base directory and type: jar cvf cs160.jar csbsju/cs160/*.class The Java™ Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications. The manifest is a special file that can contain information about the files packaged in a JAR file. By tailoring this "meta" information that the manifest contains, you enable the JAR file to serve a variety of purposes. When you create a JAR file, a default manifest is created automatically. This section describes the default manifest. Read more on jar files: Read more on setting an Application's Entry Point (using manifest file:):
67
Create a package Add jar to classpath in DrJava:
EditPreferencesResourceLocationsExtraClassPathAddselect cs160.jar ok 67 ~]$ echo $CLASSPATH should display java classpath commandline
68
Importing Packages import directive lets you refer to a class of a package by its class name, without the package prefix: import java.util.Scanner; Now you can refer to the class as Scanner without the package prefix. E.g. Scanner in = new Scanner(System.in);
69
Importing Packages Can import all classes in a package:
import csbsju.cs160.*; Never need to import java.lang. You don't need to import other classes in the same package .
70
Programming Question Import packages:
Write a tester class called PackageImportDemo which will test importing packages (save this class in a completely different location than the location you have source/.class files for cs160 package you created) Import the package you created and test BankAccount class by creating a BankAccount object with balance $1000 and printing the balance by calling toString() method:
71
Answer PackageImportDemo.java import csbsju.cs160.BankAccount;
public class PackageImportDemo { public static void main(String args[]) BankAccount acct = new BankAccount(1000.0); System.out.println(acct); }
72
References Beginning Java Objects, KN King
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.