Download presentation
Presentation is loading. Please wait.
1
Objects
2
How to Send a new Message?
Classes can accept a special message, namely new. This special message is sent as follows: new classname(parameters); On receiving this message, a new object of the indicated class will be created.
3
Constructor?! We need a constructor to construct, create, initialize a new object for us. e.g. Filling in the fields Constructor is one special kind of method of a class, bearing same name as the class. Usage: <classname> <variable_name>; <variable_name> = new <classname>(…); Constructor
4
The two methods bear the same name as the class!
Constructors Example class Boy { public int age; public Boy () { age = 0; } public Boy (int initialAge) { age = initialAge; class Family { public static void main (String[] args) { Boy michael = new Boy(); Boy anson = new Boy(3); The two methods bear the same name as the class!
5
Constructor Example class Boy { public int age; public Boy () { age = 0; } public Boy (int initialAge) { age = initialAge; class Family { public static void main (String[] args) { Boy michael = new Boy(); Boy anson = new Boy(3); There may be more than one constructors, with different parameter lists (signatures).
6
Constructor Example class Boy { public int age; public Boy () { age = 0; } public Boy (int initialAge) { age = initialAge; class Family { public static void main (String[] args) { Boy michael = new Boy(); Boy anson = new Boy(3); They normally perform some initialization for the newly created object. They must not have modifiers such as static, final, … Normally, the only permissible modifier is public.
7
Constructor Example class Boy { public int age; public Boy () { age = 0; } public Boy (int initialAge) { age = initialAge; class Family { public static void main (String[] args) { Boy michael = new Boy(); Boy anson = new Boy(3); We send two new() messages to create two new objects. The two objects are initialized by different constructors.
8
Constructor Example Boy michael = new Boy(); is equivalent to
class Boy { public int age; public Boy () { age = 0; } public Boy (int initialAge) { age = initialAge; class Family { public static void main (String[] args) { Boy michael = new Boy(); Boy anson = new Boy(3); Boy michael = new Boy(); is equivalent to Boy michael; michael = new Boy(); Remember? int i = 7; int i; i = 7;
9
Constructor Example Variables michael and anson are of type class Boy.
public int age; public Boy () { age = 0; } public Boy (int initialAge) { age = initialAge; class Family { public static void main (String[] args) { Boy michael = new Boy(); Boy anson = new Boy(3); Variables michael and anson are of type class Boy. They are for storing object references. They refer to the newly created objects. They are NOT primitive type.
10
Constructor Example michael anson age age 3 Boy Boy class Boy {
public int age; public Boy () { age = 0; } public Boy (int initialAge) { age = initialAge; class Family { public static void main (String[] args) { Boy michael = new Boy(); Boy anson = new Boy(3); Boy age michael anson Boy age 3
11
Creation of Objects: 4 Steps
According to the known resource requirement (such as memory size) of the new object, the new message will implicitly cause the Java system to allocate resources such as memory block for storing the object. The new object is then prepared with a new set of instance fields and methods, according to the class design.
12
Creation of Objects: 4 Steps
After memory allocation, the corresponding constructor method is invoked (called) to initialize the new object. An object reference is returned finally, to be stored in a field/ variable of the matching object type.
13
Object Reference Like a call number in the library.
A call number refers to a real/physical book object. No matter how many times you copy a call number, it is still referring to the same object. Holding QA c1 affects the user who borrowed the same book. Unless you copy the object, e.g. buying a new book, you won’t get a new call number. QA c1 and QA c2
14
Class with Fields and Methods
class MyVector { protected double x, y, z; protected static final int dimension = 3; public void setX (double valueX) { x = valueX; } // likewise for setY() and setZ() public double length ( ) { double answer; answer = Math.sqrt(x * x + y * y + z * z); return(answer); } This is a class. MyVector x y z dim setX( ) length( )
15
Fields Declarations Note the modifiers for the fields. x y Fields z
class MyVector { protected double x, y, z; protected static final int dimension = 3; public void setX (double valueX) { x = valueX; } // likewise for setY() and setZ() public double length ( ) { double answer; answer = Math.sqrt(x * x + y * y + z * z); return(answer); } Note the modifiers for the fields. MyVector x y Fields z dim setX( ) length( )
16
Method Declarations Note the method bodies. x y z dim Methods setX( )
class MyVector { protected double x, y, z; protected static final int dimension = 3; public void setX (double valueX) { x = valueX; } // likewise for setY() and setZ() public double length ( ) { double answer; answer = Math.sqrt(x * x + y * y + z * z); return(answer); } Note the method bodies. MyVector x y z dim Methods setX( ) length( )
17
How does a General Method Declaration Look Like?
modifiers type method_name ( parameters ) { local variable declarations and statements return expression; // depends on method type } modifier(s): public, private, static, … type: either void, a primitive type or a class type parameter(s): input to the method What’s return? To terminate (end the action of) a method May give a result to the caller (message sender).
18
Return Usage for Typed Method
If type is void, there is no result to be given. return will finish the execution of the method. In this case the return statement may be omitted. return; If type is a primitive type or a class type, the method has to produce a result of the corresponding type and return it. The pair of parentheses following return is optional. return something; return(something);
19
Can We Call a Method from Anywhere as We Wish?
Of course NOT! Why? Because Java is an Object-Oriented Programming Language! Remember! Encapsulation (Data/ Method Protection) is a famous and useful concept. We limit or grant access at appropriate levels.
20
Two Modifiers: Public and Private Methods
class AngryWife { public static char ask() ... } private static void kiss() public static void action() ask(); /* enough */ kiss(); class PoorHusband { public static void action() AngryWife.kiss(); } public static void doWrong() AngryWife.action(); class Family public static void main(String[] args) PoorHusband.action();
21
Public and Private Fields
Modifiers public and private do not only apply to methods, but also apply to fields. class AngryWife { private double accountBalance; // a private variable public final char sex = ‘F’; // a public constant public void withdraw() // a method { // only methods of AngryWife can touch private fields // but not methods of PoorHusband accountBalance -= ; ... }
22
Modifiers public and private
Modifier public indicates that a field or a method or a constructor can be referenced outside its own class, i.e. by other classes. Modifier private indicates that a field or a method or a constructor can ONLY be referenced within its own class. Modifier protected will be covered later. Somehow in between public and private.
23
Methods: Performing Tasks
Class Methods static a single copy Instance Methods non static a copy for EACH OBJECT
24
Class and Instance Methods
A method defined for a class is called a class method. e.g. A method defined for an object is called an instance method (no modifier static). Class methods are shared and used through the class. e.g. Math.sin( ) Only an object can receive instance messages, not the class. michaelAccount.deposit(100) is ok BUT NOT Account.deposit(100) static void main( ) void deposit( )
25
Example: Class and Instance Methods
class messages Instance/object messages Account createAccount static … createAccount( ) michaelAccount main static … main( ) Account deposit deposit( ) deposit( ) X withdraw withdraw( ) withdraw( ) … …
26
Why Class Methods? Intuitive and global in nature
Do not require object creation before using such class methods. e.g. Math.sin( ) is a global and commonly used method. Object factory (a programming pattern) Sometimes new and constructor is not suitable and we want a specialized class method to create object for us. (Advanced) e.g. createAccount( ) The start-up method main( ) for Java Applications JVM requires a class method static void main( ) for start-up
27
Class Method Calling Syntax
className.staticMethodName(parameters) Calling class (static) method of a class. staticMethodName(parameters) Calling class (static) method of same class (omit class name). someObject.staticMethodName(parameters) Calling class (static) method of the class of some object (automatic class name inference/ determination).
28
Instance Method Calling Syntax
someObject.methodName(parameters) Calling instance method of some object. methodName(parameters) Calling instance method of this object (itself). this.methodName(parameters) super.methodName(parameters) Calling super-class instance method of this object. To be discussed later
29
Fields: Storing Data Class Fields Instance Fields static a single copy
non static a copy for EACH OBJECT
30
Class and Instance Fields
A class field represents information shared by all instances (objects) of that class. e.g. An object’s data are called its instance fields (no modifier static). Class fields are shared and used through the class. e.g. Math.PI Only an object can bear instance fields, not the class. OOVector vectorObj = new OOVector( ); vectorObj.x = 1 is ok BUT NOT OOVector.x = 1 static double minimumBalance $100.00 double balance $123.34
31
Example: Class and Instance Fields
Account peterAccount static minimumBalance $100.00 michaelAccount Account Account static createAccount( ) balance $716.00 X balance $123.45 balance deposit( ) deposit( ) deposit( ) X withdraw( ) withdraw( ) withdraw( ) … … …
32
Why Class Fields? Intuitive Saves memory space
e.g. minimumBalance is kept once for all accounts in a bank rather than storing individually in each object. Saves memory space Only keep a single copy in the class. Avoid updating multiple copies of data values Consistency concern. Efficiency concern.
33
Class Field Referencing Syntax
className.staticfieldName Referring to class (static) field of a class. staticfieldName Referring to class (static) field of same class (omit class name). someObject.staticFieldName Referring to class (static) field of the class of some object (automatic class name inference/ determination).
34
Instance Field Referencing Syntax
someObject.fieldName Referring to instance field of some object. fieldName Referring to instance field of this object (itself). this.fieldName To be discussed later
35
Concluding Remark Class (static) methods and class (static) fields are seldom defined in this course. So far, … static … main(…) is a special case. We must define it. However, we often make USE of class methods and class fields, e.g. Math.sin( ), Math.PI, etc.
36
Concluding Remark Under most circumstance, we define instance methods and instance fields in our own classes. We MUST create new object(s) before using instance methods and fields.
37
Note Only instance methods should normally “touch” instance fields, of an object itself. Class methods should normally “touch” only class fields, of a class itself. Class fields are shared amongst all the objects/ instances of a class.
38
Variables VS Constants
A data item that can change over time is called a variable. A data item that cannot change over time is called a constant . Account static minimumBalance $100.00 michaelAccount static final accountPrefix 217 Account X balance balance $123.45 X final String name name Michael
39
Soul of Object Oriented Programming
Encapsulation Protecting Data and Method: Class and Object Access Control Modularity Structured Class and Method: Divide-and-Conquer Inheritance Extends Mechanism: Reuse-and-Build Related Classes Polymorphism Dynamic Type Binding: Type-Oriented Method Invocation
40
class Account Sub-classing minBalance balance Sometimes, we want to create a new class which supplements an existing class while keeping the original class. Add new fields Add new methods Modify original components Extends class CurrentAccount minBalance balance noChequesIssued
41
How to Do it in Java? We do it using the extends mechanism.
class Original { // class field // instance field // constructor method // class method // instance method } class Subclass extends Original { /* * ALL the non-private original * fields and methods are * inherited in this new Subclass * UNLESS we modify them. */ // We may optionally: // add class field // add instance field // add constructor method // add class method // add instance method }
42
class field default value overridden
Inheritance minBalance class Account $100.00 Subclasses can be defined conveniently using inheritance. Several subclasses can inherit from the same superclass. A subclass can override inherited components (fields and methods). A subclass can add new components as well. minBalance class SavingAcct $250.00 minBalance noChequesIssued class CurrentAcct $100.00 class field default value overridden new instance field
43
CurrentAccount is a subclass of the superclass Account.
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
44
The main() method may reside in either class or even in another class.
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
45
We create a new object of class CurrentAccount
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
46
Surprisingly, the instance method deposit() can be invoked!!!
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
47
It is because the method is inherited from Account by CurrentAccount.
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
48
There’s no problem in sending message to methods of CurrentAccount.
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
49
The field noChequesIssued can be used without any concern.
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
50
How come we could access the field balance?!
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
51
Again, it’s inherited from the superclass.
Example class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
52
Example Features to be explained later…
class Account { // class field public static double minBalance = ; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; public void withdraw(double amount) { balance -= amount; class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque();
53
Inheritance Hierarchy
Inheritance is not limited to one level. Superclasses and subclasses form an inheritance hierarchy.
54
Advantages of Inheritance
To re-use and to extend existing classes. To define a “concept” more specifically. e.g. Car Benz, BMW Account CurrentAccount, SavingAccount Cake CheeseCake, ChocolateCake Window WindowWithButton, BlueWindow
55
Concerns of Inheritance
A complete and cross-referencing documentation system is needed, for example, JavaDoc to check the superclass of the superclass of the superclass of the class PrintStream to look up what fields and methods are inherited An Integrated Development Environment is preferred (IDE) such as NetBeans.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.