Objects

An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods. An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

Classes

Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.

Instance and Class variables

Instance variable are those variables that are associated with each object uniquely

Each instance of the class will have its own copy of each of these variables. Each object will have its own values for each instance variables that differentiate one object from the other of the same class type. Declared in the usual way and can have an initial value specified.

Class variables are associated with the class and is shared by all objects of the class

There is only one copy of each of these variables no matter how many class objects are created. They exist even if no objects of class have been created. These variables are also called static fields because we use the keyword static when we declare them.

Instance Methods

These methods can only be executed in relation to a particular object. If no object exists, no instance method can be executed. Note: Although instance methods are specific to objects of a class, there is only one copy of an instance method in memory that is shared by all the objects of the class.

Class Methods

You can execute class methods even when no objects of a class exist. Like class variables, these are declared using the keyword static, so also called static methods. Static methods cannot refer to instance variables or call instance methods. Why? Why main is always declared static?

Instance Variables

public class StudentRecord {
	// Instance variables
	private String name;
	private int age;
	private double mathGrade;
	private double englishGrade;
	private double average;
	//we'll add more code here later
}

Declare instance variables as private so that only class methods can access them directly.

Class (static) variables

public class StudentRecord {
//static variables
private static int studentCount;
//we'll add more code here later
}

We use the keyword static to indicate that a variable is a static variable.

Accessor (Getter) Method

public class StudentRecord {
private String name;
// some code
// An example in which the business logic is
// used to return a value on an accessor method
	public double getAverage(){
	double result = 0;
	result=(mathGrade+englishGrade+scienceGrade)/3;
	return result;
	}
}

Mutator (Setter) Method

public class StudentRecord {
	private String name;
	public void setName( String temp ){
	name = temp;
	}
}

Static methods

public class StudentRecord {
	private static int studentCount;

	public static int getStudentCount(){
		return studentCount;
	}
}

Static-means that the method is static and should be called by typing,[ClassName].[methodName].  For example, in this case, we call the method StudentRecord.getStudentCount()

Sample Source Code that uses StudentRecord Class

public class StudentRecordExample
{
public static void main( String[] args ){
//create three objects for Student record
StudentRecord aRecord = new StudentRecord();
StudentRecord bRecord = new StudentRecord();
StudentRecord cRecord = new StudentRecord();
//set the name of the students
aRecord.setName(“Alistair");
bRecord.setName(“Micheal");
cRecord.setName(“David");
//print name
System.out.println( aRecord.getName() );
//print number of students
System.out.println("Count="+StudentRecord.getStudentCount());
}
}

An Example – BankAccount

public class BankAccount {
  //--instance variables
  private String ID;
  private double balance;
    // Constructor to initialize the state
  public BankAccount(String initID, double initBalance) {
    ID = initID;
    balance = initBalance;
  }
  // Credit this account by depositAmount
  public void deposit(double depositAmount) {
     balance = balance + depositAmount;
 }
  // Debit this account by withdrawalAmount
 public void withdraw(double withdrawalAmount) {
    balance = balance - withdrawalAmount;
 }
  public String getID() {
    return ID;
  }
  public double getBalance() {
    return balance;
  }
  public String toString( ) {
    return ID + " $" + balance;
  }
} // End class BankAccount

Sample Message

BankAccount anAcct = new BankAccount("Moss", 500.00);    
anAcct.withdraw(60);
anAcct.deposit(147.35);

Overloading Methods

Method overloading allows a method with the same name but different parameters, to have different implementations and return values of different types. It can be used when the same operation has different implementations. Always remember that overloaded methods have the following properties:

  • the same method name
  • different parameters or different number of parameters
  • return types can be different or the same

Default Constructor (Method)

It is the constructor without any parameters.  If the class does not specify any constructors, then an implicit default constructor is created.

Overloading Constructors

  • —Classes can have more than one constructor
  • All constructors have the same name (the class name)
  • Each constructor differs from the others in either the number or types of its arguments
  • New is used when using a constructor to create a new object
Overloading Constructor Methods
public StudentRecord(){
//some initialization code here }
public StudentRecord(String temp){
this.name = temp; }
public StudentRecord(String name, String address){
this.name = name;
this.address = address;
}
public StudentRecord(double mGrade, double eGrade,double sGrade){
mathGrade = mGrade;
englishGrade = eGrade;
scienceGrade = sGrade;
}

To use these constructors, we have the following code,

public static void main( String[] args ){
//create three objects for Student record
StudentRecord aRecord=new StudentRecord(“Ahmed");
StudentRecord bRecord=new StudentRecord(“BIT“, “Pakistan");
StudentRecord cRecord=new StudentRecord(80,90,100);
//some code here
}

“this()” constructor call

Constructor calls can be chained, meaning, you can call another constructor from inside another constructor. We use the this() call for this object. There are a few things to remember when using the this() constructor call:

  • When using the this constructor call, it must occur as the first statement in a constructor
  • It can only be used in a constructor definition. The this call can then be followed by any other relevant statements

Example

public StudentRecord(){
this("some string");
}
 public StudentRecord(String temp){
 this.name = temp;
 }
 public static void main( String[] args )
 {
	 StudentRecord aRecord = new StudentRecord();
 }

this reference refers to current object instance itself. It is used to access the instance variables shadowed by the parameters. To use the this reference, we type, this.<nameOfTheInstanceVariable>. You can only use this reference for instance variables and NOT static or class variables. The this reference is assumed when you call a method from the same object

public class MyClass {
	void aMethod() {
		// same thing as this.anotherMethod()
	anotherMethod();
	}
	void anotherMethod() {
	// method definition here...
	}
}
public void setAge( int age ){
	this.age = age;
}

Tagged with: ClassesJAVAObject OrientedProgramming
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.