Jan. 29 Tue. Class Notes
Objectives
Review
Object & Class
Instance & Class Variable
Instance & Class Method
public, private, final, abstract
----------------------------------------
Pass Message to a Program --- revisit
class Hello {
public static void main(String[] args) {
String str = "Judy";
if (args.length > 0) {
str = args[0];
}
String msg = "Hello " + str ;
System.out.println(msg);
}
}
>java –cp . Hello Kathy Bob Dan
Hello Kathy
NOTE: Any single message passed through command line
is a String object. args holds a collection of String objects
----------------------------------
Reference Type vs Primitive Type
A reference type or an object can never be casted to a primitive type
A primitive type can never be casted to a reference type or an object type
String s = “123”;
int i = s; // illegal
int i2 = (int)s; //illegal
Use 8 wrapper classes to convert String object to primitive types.
String s = “123”;
byte b = Byte.parseByte(s);
short s = Short.parseShort(s);
int i = Integer.parseInt(s);
long lg = Long.parseLong(s);
float f = Float.parseFloat(s);
double d = Double.parseDouble(s);
-----------------------------------
void keyword is used to indicate that a method returns no value.
-----------------------------------
null can be assigned to any reference type to indicate an absence of reference
null is a special value that is a reference to nothing
null is printable
null is used to initialize an object type
-----------------------------------
new operator is used to allocate memory for object and arrays.
-----------------------------------
Object Creation with new
ObjectType obj = new ObjectType();
ObjectType obj2 = new ObjectType(parameter list);
-----------------------------------
public class First extends Object {
//default constructor
public First() {
super();
}
public static void main(String[] args) {
System.out.println(“First Java Program”);
}
}
------------------------------------
How to print out “First Java Program” with new operator
You have to write a method to do so
class First {
public static void main(String[] args) {
System.out.println(“First Java Program”);
}
public static void print() {
System.out.println(“First Java Program”);
}
}
First.print(); //First Java Program
First f = new First();
f.print(); // First Java Program
-----------------------------------
What is the default constructor?
Default constructor is a constructor that takes no arguments
If you define no constructors at all in a class, then the
compiler provides a default constructor. If you define even
a single constructor, this default is not provided.
-----------------------------------
What is the construtor?
A constructor is a special method used to create an object with
new operator
A constructor must have the same name as the class
Constructors do not have a return type
Generally constructors are used to initialize the data fields
Constructors can be overloaded.
-----------------------------------
Use Default Constructor
First f = new First();
Hello h = new Hello();
Judy j = new Judy();
Tester t = new Tester();
DollarChanger dc = new DollarChanger();
------------------------------------
Basic structure of a class
[modifier] class clsIdentifier [extends clsIdentifier implements interfaceIdentifier, , ] {
Attributes or Properties block (fields)
Methods
}
-----------------------------------
How the attributes look like in a class?
class foo {
//attributes block
private int creditCardNo;
public static final double PI = 3.1415926;
String name;
protected char midName;
……
public static format(double d, int I) {}
...
}
Attributes are represented by class fields and instance fields.
-----------------------------------
Members of a Class
1. Class fields
2. Instance fields
3. Class methods
4. Instance methods
-----------------------------------
What is the class field?
1. A class field is declared with static modifier
2. A class field is associated with the class in which it is defined.
class Foo {
public static final double PI = 3.1415926;
public static String initial = “JX”;
static double int counter;
...
}
-----------------------------------
What is the class method?
1. A class method is declared with the static modifier
2. A class method is associated with a class, rather
than with an object.
e.g.
public static double format(double d, int i) {}
static String print() {}
public static int add(int a, int b) {}
-----------------------------------
What is the instance fields?
Any fields declared without the static modifier
class Foo {
public int sum;
public Calculator cal;
final char midInitial = ‘X’;
....
}
-----------------------------------
What is the instance methods?
1. Any method not declared with the static modifier is an instance
method.
2. An instance method operates on an instance of a class(an object)
instead of operating on the class itself
3. It requires an instantiated object of the class in order to be
invoked.
-----------------------------------
How to call a class method?
1. className.staticMethod()
2. new className().staticMethod()
double d = Sara.format(3.4445, 2);// 3.44
Sara sr = new Sara();
double d2 = sr.format(3.4445,3);//3.445
int i = Calculator.add(5,5); //10
int i2 = new Calculator().mul(5,5); //25
-----------------------------------
How to call an instance method?
Instantiate an object with new operator and then use the
instance variable to call the instance method
class Foo {
public void report() {…}
long cal(long a, long b) {…}
public String getName() {…}
...
}
Foo f = new Foo();
String name = f.getName();
-----------------------------------
private keyword
1. The least generous access modifier
2. Applies to member variables, methods, constructors or inner classes.
3. Visibility is inside the class and hidden everywhere else.
private String creditCardNo;
private int creditRanking(){}
-----------------------------------
final keyword
1. Applies to classes, methods, and variables.
2. A final variable(primitive types) may not be modified once it
has been assigned a value
3. A final class may not be subclassed.
4. A final method may not be overridden.
5. A final variable(reference type) must stay the same, not the object.
-----------------------------------
abstract keyword
1. Applies to classes and methods
2. May not be instantiated(may not call its constructor)
3. Provide a way to defer implementation to subclasses
4. Abstract class must be subclassed
abstract class Student { }
abstract String getStatus();//abstract method, no method body
String getStatus() {} //not abstract
------------------------------------
Create an Employee class
Attributes:
Employee Number -- int
Employee Last Name -- String
Employee First Name -- String
Employee Salary – double
Company Number - int
Employee Address –String
Employee Telephone – String
Employee Birthdate – Date
............
------------------------------------
important points in the Employee class
encapsulation
data hiding or info hiding
member variables initialized by default values
------------------------------------
public class Employee {
private int num;
private String lastName;
private String firstName;
private double salary;
public static int companyID = 8888;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String name) {
lastName = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
String str = "Employee Number: " + num
+"\nFirst Name: " + firstName
+ "\nLast Name: " + lastName
+ "\nSalary:$" + salary;
return str+"\n";
}
public static void main(String[] args) {
Employee e1 = new Employee();
System.out.println(e1);
e1.setNum(1234);
e1.setFirstName(“Judy”);
e1.setLastName(“XU”);
e1.setSalary(200.0);
System.out.println(e1);
e1.setNum(3456);
System.out.println(e1);
Employee yn = new Employee();
System.out.println(yn);
yn.setNum(2356);
yn.setFirstName(“XXX”);
yn.setLastName(“XXXX”);
yn.setSalary(500.0);
System.out.println(yn);
System.out.println(yn.getLastName()); //yln
String name = yn.getFirstName();
System.out.println(name); //yfn
double salary = yn.getSalary();
System.out.println(salary); //dbl value
System.out.println(e1.getSalary()); //200.00
//See how the class field associated with class itself
//Class variables are variables that are shared by every
//instantiation of a class
System.out.println(Employee.companyID); //8888
System.out.println(e1.companyID); //8888
System.out.println(yn.companyID); //8888
}
}
------------------------------------
Pitfalls:
Non-static method cannot be called in a static method.
Non static variable cannot be used by static methods
Illegal statements in main():
System.out.println(num); //illegal
String name = getFirstName(); //illegal
System.out.println(getFirstName()); //illegal
setFirstName(“Judy”); //illegal
------------------------------------
Lab
Compile and run Employee class
Copy contents in main() of Employee class to the main()
in YourName class and compile and run YourName class.
Practice with private keyword
Add properties to YourName class
Practice with static field
------------------------------------
Try to get a private field.
System.out.println(yn.salary);
Error:
salary has private access in Employee
------------------------------------