Classes And Objects
Java is strictly an Object-Oriented Programming Language.
Java code Class Interface
Classes
Describe the objects attributes behaviors
Class is a description of an object.
Object is defined to be an instance of a class
An Object consists of attributes behaviors
An attribute is a feature of the object, something the object has.
A behavior is something the object does
Each attribute of an object is denoted as a field in the class
Each behavior of an object becomes a method in the class
Procedural Programming
Flowcharts Decomposition Procedures
Object-Oriented Programming
Classes Objects Inheritance Encapsulation Polymorphism
Payroll Program
Determining objects in problem Employees Company Payroll department more objects.
Employee Class
Attributes name address national id number Behaviors hours worked() pay()
Writing a Java class
class (keyword)
public class Employee {
Employee class
public class Employee { public String name; public String address; public String id; public double hPay; }
public class Employee { public String name; public String address; public String id; public double hPay; public void writeDetails { System.out.println(name + + id); } }
public class Employee { public String name; public String address; public String id; public double hPay; public double computePay { return hPay * 40; } }
public class Vehicle { int pasg; int fCap; int mpg; }
Creating Vehicle object
Vehicle jeep = new Vehicle();
Dot (.) operator
Object.member
Dot operator
jeep.fCap = 16;
Instantiating an Object
Vehicle jeep ;
jeep = new Vehicle() ;
Create an object in memory and returns a reference
reference jeep is pointing to the Vehicle object in memory
jeep.psg = 8 ; jeep.fCap = 24 ; Jeep.mpg = 44 ;
car.psg = 4 ; car.fCap = 18 ; car.mpg = 28 ;
Constructor
Initializes an object when its created. Has the same name as its class. Syntactically similar to a method. Has no explicit return type.
Give initial values to the instance variables. Perform startup procedures.
Constructor
All classes have constructors. Java automatically defines default constructor that initializes all member variables to zero.
Garbage Collection
Vehicle jeep = new Vehicle() Vehicle jeep = new Vehicle()
Vehicle jeep = new Vehicle()
Vehicle jeep = new Vehicle()
Vehicle j1 = new Vehicle();
Vehicle j2 = new Vehicle();
j1
j2
Vehicle j3 = j2;
j3
Vehicle j1 = new Vehicle();
Vehicle j2 = new Vehicle();
j1
j2
Vehicle j3 = j2;
j3
j1 = j2;
The finalize() Method
Called just before an objects final destruction by the garbage collector. protected void finalize() { // code }