Upload
audrey-salinas
View
14
Download
1
Embed Size (px)
DESCRIPTION
Creating Instances. Think of a class as a blueprint. The blueprint isn’t the house. It’s the plans for a house. From that blueprint (or class) you can make many instances(objects) of that house. Let’s say we have our Rectangle class. - PowerPoint PPT Presentation
Citation preview
Creating Instances
• Think of a class as a blueprint.
• The blueprint isn’t the house. It’s the plans for a house.
• From that blueprint (or class) you can make many instances(objects) of that house.
• Let’s say we have our Rectangle class.
• We can create multiple “instances” of that class like this:
Rectangle box1 = new Rectangle(); • Now we have a Rectangle object named “box1”
Rectangle box2 = new Rectangle();• Now we have a Rectangle object named “box2”
• Each Rectangle object (or instance) has access to the Rectangle class’ procedures and data fields.
• However, each Rectangle object has its own INSTANCE of those procedures and data fields.
• Ex:Data (Fields)
----------------------------------
Methods That Operate on the Data
-dblLength = 5
-dblWidth = 10
-setLength( )
-setWidth( )
-getLength( )
-getWidth( )
-calcArea( )
Data (Fields)
----------------------------------
Methods That Operate on the Data
-dblLength = 3
-dblWidth = 7
-setLength( )
-setWidth( )
-getLength( )
-getWidth( )
-calcArea( )
box1 box2- This variable holds the memory address of this Rectangle object
- This variable holds the memory address of this Rectangle object
• Instance Variables:
– Also known as instance fields.
– The variables in each separate instance of the class.
– For example, each instance of the Rectangle class has its own dblLength and dblWidth variables.
• Instance Methods:
– Also known as instance procedures.
– The methods in each separate instance of the class.
– For Example:• box1 This instance has its own setLength method.• box2 This instance has its own setLength method.
– Instance methods do not have the keyword “static” in their method headers.
• Main methods usually are written like this:public static void main( )
• Methods in other classes are written like this:
public void getLength( )
Why is static there?
Why do we not put static there?
• Static:
– A header declaration that tells Java whether or not multiple instances of a variable or method are allowed.
– If a data member(variables and methods) is static, that means that it is the only ONE.
– There can not be multiple instances of something if it is static.
– For example, if you see this:
public static void main( )
– There can only be ONE instance of the main method. It is static.
Main
------------------
Main ( )
– If you see this:
public void getLength( )
– There can be multiple instances of the getLength method. It is NOT static.
box2
------------------
getLength ( )
getWidth( )
box3
------------------
getLength ( )
getWidth( )
box1
------------------
getLength ( )
getWidth( )