What We Will Cover
Illuminations
Homework Questions?
Homework Discussion Questions
- What was the hardest part of the assignment?
- For C++ programmers new to Java, how similar does Java seem to C++ so far?
- Is it hard to make an executable JAR file?
^ top
4.1: Classes and Methods
Learner Outcomes
At the end of the lesson the student will be able to:
- Describe the rationale for object-oriented programming
- Describe how to declare a class
- Declare instance variables
- Define and call simple instance methods
|
^ top
4.1.1: Introduction to Objects and Classes
- Java programs consist of objects that interact with each other
- Because of this, Java is known as an object-oriented programming language
- This means that when you program in Java you focus on objects
Why Objects?
Software Objects
- In object oriented programs, we use our ability to work with objects to solve software problems
- However, when we develop software we have to make things simpler than in the real world
- How do we simplify without losing the essence of the object?
- We can simplify using a concept called abstraction
- Abstraction: taking away inessential features, until only the relevant parts of the concept remains
Describing Software Objects
^ top
4.1.2: Declaring a Class
Class Declaration -- First Attempt
1
2
3
4
5
6
7
8
|
public class Product1 {
public String name;
public double price;
public void print() {
System.out.println(name + " @ " + price);
}
}
|
Testing the Class
- To run the example class we write another class for testing
- We can start with a simple
main() method that instantiates two objects, assigns values to variables and calls a method
Test Class for Class Declaration
1
2
3
4
5
6
7
8
9
10
11
12
|
public class ProductTest1 {
public static void main(String[] args) {
Product1 milk = new Product1();
milk.name = "Whole milk";
milk.price = 4.59;
Product1 bread = new Product1();
bread.name = "Wheat bread";
bread.price = 2.99;
milk.print();
bread.print();
}
}
|
More Information
^ top
4.1.3: Instance Variables
- Recall the following two lines from the class declaration:
public String name;
public double price;
- These variables are known as instance variables, member variables or fields:
Instance variable: a variable defined in a class for which each object (instance) has a separate copy.
- The word
public means that there is no restriction on their use
- To make use of instance variables, we must first instantiate an object:
Product1 milk = new Product1();
- The
new operator allocates memory space for each instance variable
- After instantiating an object, we can assign values to the variables:
milk.name = "Whole milk";
milk.price = 4.59;
- Each object has its own copy of instance variables:
Product1 bread = new Product1();
bread.name = "Wheat bread";
bread.price = 2.99;
- Thus we can assign different values to the variables in different objects
- Together, the
milk and bread objects have four instance variables
More Information
^ top
4.1.4: Introduction to Methods
Method -- a named block of code defined inside a class.
- In other languages, a method is known as a function, procedure or subroutine
- Our
Product1 class has only one method definition:
public void print() {
System.out.println(name + " @ " + price);
}
- All method definitions belong to some class and are defined in the class to which they belong
- A method definition has two parts:
- You call a method you write the same way you call a method for a predefined class
- When we call a method, we pass the flow of control to the method
- In this case, the method executes the single statement:
System.out.println(name + " @ " + price);
- When the method finishes executing all its statements, the flow of control returns to the calling point
- In this case, the caller was one of these lines in the
main() method of ProductTest1:
milk.print();
bread.print();
- Both of these method calls transferred control to the
print() method of the Product1 class
- Both times the method returned after executing the last command of the method
^ top
4.1.5: Summary
- Java programs primarily consist of objects that interact with each other
- An object is a person, place or thing that either performs some action in a situation or is acted upon
- Software objects are often simplifications or real world objects
- The process of simplifying real world objects without losing their essential features is known as abstraction
- To describe a software object, we write code for both data and actions
- We write all the code describing an object in a single software construct called a class
- The class is like a blueprint and is the set of rules for creating an object
- All Java code is written using classes
- A class uses instance variables to store the data for an object
- The actions that an object can perform are defined in methods
- A method is a set of statements that performs a specific task
- When you want the statements executed, you call the method
Check Yourself
- What is a class?
- What is an object?
- What is the difference between a class and an object?
- What is the syntax for declaring a class?
- What is a method?
- Where are methods defined?
^ top
Exercise 4.1
Take one minute to prepare an answer the following questions.
- Add a method to the
Product1 class named initialize() that sets the instance variable name to "none" and the instance variable price to 0.
- Update the
ProductTest1 class to call the initialize() method for each object
^ top
4.2: More About Methods
Learner Outcomes
At the end of the lesson the student will be able to:
- Write methods for classes
- Pass values to methods
- Return values from methods
- Code
void return types for methods
|
^ top
4.2.1: Enhancing Our Class
- Recall that methods are a named block of code defined inside a class
- We looked at an example method:
public void print() {
System.out.println(name + " @ " + price);
}
- The name is specified in the method heading, in this case print
- The method body contains the statements to execute, which are defined inside the curly braces
- Many methods have input values (a.k.a. arguments or parameters) that are transferred or passed into the method
- We have used methods that take arguments such as
"Hello, World!" in:
System.out.println("Hello, World!");
- Many methods have output or return values
- For example, the
name in: name = input.nextLine();
- In general, we categorize methods into two kinds:
- Methods that return a value
- Methods that perform an action without returning a value
- Methods that do not return a value are often called
void methods
Improving Our Class
- In the following example we enhance our product class by adding more methods
- In addition, we change the access modifier of the instance variables from
public to private
- The word
private means that only members of this class can access the variable
- As a rule of thumb, you should declare all instance variables
private
- We will discuss the rationale for declaring instance variables
private in a later section
Example Class -- Second Attempt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import java.util.Scanner;
public class Product2 {
private String name;
private double price;
public void print() {
System.out.println(name + " @ " + price);
}
public void read() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the product name: ");
name = input.nextLine();
System.out.print("Enter the product price: ");
price = input.nextDouble();
input.nextLine(); // clear whitespace
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setPrice(double newPrice) {
price = newPrice;
}
}
|
Test Class for Example Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import java.util.Scanner;
public class ProductTest2 {
public static void main(String[] args) {
Product2 milk = new Product2();
Product2 bread = new Product2();
milk.read();
System.out.println();
bread.read();
milk.print();
bread.print();
System.out.print("\nEnter price increase: ");
Scanner input = new Scanner(System.in);
double increase = input.nextDouble();
double milkPrice = milk.getPrice();
milk.setPrice(milkPrice + increase);
double breadPrice = bread.getPrice();
bread.setPrice(breadPrice + increase);
milk.print();
bread.print();
}
}
|
^ top
4.2.2: Defining Methods
Access Modifier
- The access modifier specifies which classes can use your method
- The word
public means the method can be accessed by any class
- If we used
private, then the method can only be accessed from inside the class
- You can think of this as a privacy feature
- If you keep a journal on the Web (a blog) then it is public and anyone can read it
- However, if you keep a journal on your personal computer, then it is private and only you can read it
- Use a
public access modifier for methods for now
- Later we will discuss when to use
private
Return Type
- Sometimes you will want a method to return a value
- If you do, then you need to specify the type of data it will return
- If you do not want a method to return a value, then you use the keyword
void
Method Name
- Technically, you can use any valid identifier for a method name
- However, professional programmers follow naming conventions, which include:
- Use a name that suggests its meaning
- Use verbs to name methods, since they perform an action
- Start method names with a lower case letter
- Separate multiple-word names by starting each word (after the first) with a capital letter
- Since you and I both want your code to look professional, you must follow these conventions
- More information: The Java Language Specification: 6.8.3 Method Names
Parameter List
- You must have parenthesis after the method name
- Inside the parenthesis, you define a list of parameters, if any
- Parameters are like variables except they are declared inside the method parenthesis
- Each parameter must have both a type and a name, like a variable
- If you have more than one parameter, you separate each one with commas
- A parameter type can be any primitive type or class type, like a variable
- Any parameter that you declare must be given a value when you call the method
Code Block
- After the parenthesis, you define the block of code that you want to execute
- The block starts with an opening curly brace: {
- The block ends with a closing curly brace: }
- Between the curly braces, you list all the statements you want the method to execute
More Information
^ top
4.2.3: Returning a Value
- Recall that methods can return values and that every method has a return type
[accessModifier] returnType methodName(parameterList) {
statements
}
- Until now we have used
void for all our method return types:
public void print() {
System.out.println(name + " @ " + price);
}
- However, we can declare a method that gives back a specific type to the caller, like:
public double getPrice() {
return price;
}
- If you declare that a method will return a value, you must return a value of the correct type
- The way you return a value is to use a
return statement
- For example:
return price;
- When you call a method that returns a value, then you must save the return value or you will lose it:
double milkPrice = milk.getPrice();
- Sometimes you may just want to immediately use the returned value, like:
System.out.println("Price: " + milk.getPrice());
- If you do not need to use the returned value again, there is no need to assign it to a variable
More Information
^ top
4.2.4: Local Variables and Blocks
- Look at the definition of the method
read():
public void read() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the product name: ");
name = input.nextLine();
System.out.print("Enter the product price: ");
price = input.nextDouble();
input.nextLine(); // clear whitespace
}
- This method includes the declaration of the variable
input
- A variable declared inside a method is called a local variable
Local variable: a variable that is only accessible within the block or method within which it is declared.
- It is called a local variable because it can only be used inside the method in which it is declared
- On the other hand, an instance variable can be used in any method of the class
- The difference is a matter of scope:
Scope: the region of a program that a variable or other program item is accessible.
- Scope is delimited by curly braces
{ }
- The set of curly braces is known as a block
- If you declare a variable inside a block, that variable is local to that block
- This means that when the block ends, all variables declared in the block disappear
- If you declare a variable outside a block, you can use the variable either inside or outside the block
- In the following example, the first commented variable declaration causes a compiler error (if uncommented)
- You cannot have more than one variable declaration in a method
- The second commented statement causes a compiler error (if uncommented) because the
int i is declared in the scope of the for loop
Block Testing
1
2
3
4
5
6
7
8
9
|
public class BlockTester {
public static void main(String[] args) {
// int i;
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
//System out.println("At end, i=" + i);
}
}
|
^ top
4.2.5: Method Parameters
- Like other programming languages, you can pass arguments into your methods
- Here is a method with a parameter from our example class:
public void setPrice(double newPrice) {
price = newPrice;
}
- The parameter is
double newPrice in the parenthesis of the method heading
- Note that parameters look like variable declarations
- That is because parameters are local variables except for one key difference
- The difference between parameters and local variables is that parameters are initialized by arguments made in the method call:
milk.setPrice(milkPrice + increase);
- In this example, the program computes
(milkPrice + increase) and passes the computed value to newPrice
- In the
setPrice() method, the newPrice parameter is initialized to the value passed from the method call
- For example, if the value of
(milkPrice + increase) is 4.79 then newPrice is initialized to the value 4.79
- The parameter is initialized by copying the value 4.79 from the method call to
newPrice
- After being initialized, the parameter works like any other local variable
- You can access parameter values, like:
price = newPrice;
- Also, you can assign parameter variables new values, like:
newPrice = newPrice + 0.25;
- When the method finishes executing, the
newPrice value disappears
Arguments and Parameters
Coercion of Arguments
Call-By-Value
- In Java, all arguments are passed to parameters by value (a.k.a. call-by-value)
- A method only gets a copy of an argument's value
- Changes to the parameter variable inside a method do not affect the value of a calling argument
- You can see the effects of call-by-value in the following example
Testing Call-By-Value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class PassByValue {
public static void main(String[] args) {
int x = 2;
PassByValue pbv = new PassByValue();
pbv.passMethod(x);
// print x to see if its value has changed
System.out.println(
"After calling passMethod, x = " + x);
}
// Change parameter in passMethod()
public void passMethod(int p) {
p = 100;
}
}
|
More Information
^ top
4.2.6: Overloading Methods
- You can have several methods with the same name in a class
- However, each method must have a different parameter list for each method:
- Number of parameters
- Parameter types
- Order of parameters
- For example we could have all of these methods in a class
void print(String s) {
System.out.println(s);
}
void print(String s, int i) {
System.out.println(s + ", " + i);
}
void print(int i, String s) {
System.out.println(s + ", " + i);
}
- The method name and parameter list together are known as the method signature
- Note that the return type is not part of the signature
- The compiler cannot distinguish between two methods with the same signature but different return types
- The following example demonstrates method overloading
Example Demonstrating Method Overloading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class OverloadingDemo {
public static void main(String[] args) {
OverloadingDemo od = new OverloadingDemo();
od.print("String only");
od.print("String first", 7);
od.print(7, "int first");
}
void print(String s) {
System.out.println(s);
}
void print(String s, int i) {
System.out.println(s + ", " + i);
}
void print(int i, String s) {
System.out.println(s + ", " + i);
}
}
|
^ top
4.2.7: Summary
Check Yourself
- Which of the following is a method definition and which is a method call?
public double getPrice() { }
milk.getPrice();
- What statement is used to return values from methods?
- Can methods be declared in other methods?
- Why do methods sometimes need parameters?
- If you declare three parameters, how many arguments must you include in a method call?
- What are the differences between local variables and instance variables?
- What is meant by the term argument? parameter?
- What do local variables and parameter variables have in common?
- In which essential aspect do local variables and parameter variables differ?
- How many methods with the same name can you define in a class?
- If two methods have the same name, what must be different in each definition?
^ top
Exercise 4.2
Take one minute to prepare an answer the following questions.
- Which of the following are valid method declarations?
methodA() { /*...*/ }
void methodB { /*...*/ }
void methodC() { /*...*/ }
void methodD(void) { /*...*/ }
^ top
4.3: Encapsulation and Data Hiding
Learner Outcomes
At the end of the lesson the student will be able to:
- Discuss the concept of encapsulation and information hiding
- Design and implement accessor and mutator member methods
- Design and implement
toString() methods
|
^ top
4.3.1: Encapsulation and Information Hiding
- As programs become larger, we need to change the way we work on them
- Large programs usually have teams of people who work on them like:
- One or two software engineers may work on the user interface
- Another two or three may work on the logic of the application and various features
- Another may work on data storage and retrieval
- When many programmers work together, they need to take special care with the data
- The data type of an application may need to change as the program develops
- For example, we may start a program by keeping money in a variable of type
double
- Later we may decide that two
int variables are a better choice (dollars and cents)
- Any part of the program that used the
double variable would have to change
The Prescription for Larger Programs
- To make larger programs more manageable, we use classes
- Two important features of classes are:
- Encapsulation
- Information hiding
- These two concepts are closely intertwined
- Sometimes you will see a reference to one term when the writer means both terms
Encapsulation
Encapsulation: inclusion of a number of items into a single unit
- We saw an example of encapsulation when we looked at our first product class
- Encapsulation allowed us to group related variables in one container (capsule)
- If the variables in the grouping are logically related, we can more easily keep track of what is happening with the data
- For example, we can keep all the data about a product inside one container
- In addition to data, classes extend encapsulation to include member methods
- Member methods are methods that work with the member variables
- Thus, methods like
print() are grouped into the class that describes a product
Information Hiding
Information hiding: hiding the parts of the design that are most likely to change (a.k.a. data hiding)
- As programs develop, developers change them frequently
- Even after a program is first completed and released, successful programs are updated with new features
- With large programs, making a change in one area can cause problems in other areas
- By hiding the parts of a program most likely to change, a programmer can make implementing changes much easier
- The ability to change parts of a program without affecting other parts becomes more important as programs grow larger
^ top
4.3.2: Private Data
- Recall that the instance variables of our example classes
- In the first example we declared the variables with the modifier
public:
public String name;
public double price;
- Yet in the second example we declared the variables
private:
private String name;
private double price;
- The modifier
public means there are no restrictions on accessing the variables
- The modifier
private means the variable accessed outside of the class
- We could test this feature by writing a test like the following:
Product2 milk = new Product2();
milk.name = "Whole milk";
milk.price = 4.59;
- If we try to compile this code, then we get an error message
- However, if we remove the keyword
private, then the test code compiles without error
- So why bother with
private data?
- Good software engineering practice says you should almost always declare class variables
private
- One of the exceptions is that constants may be declared
public
- There are other rare cases, but you will not run across them in this course
- Thus, for this course, always declare non-constant instance variables
private
- The most important reason is to hide the internal implementation details of the class
- You want to prevent programmers from relying on those details
- This lets you safely modify your class implementation at any time without worrying that you will break code that uses the class
^ top
4.3.3: Accessor and Mutator Methods
- You should always make all instance variables of a class private
- However, you still may need to do something with the data of a class object
Mutator Methods
Accessor Methods
Get and Set Methods
More Information
^ top
4.3.4: Another Product Class
- Let us update our product class with some new methods
- We will add a setProduct() method to set both a name and price together
- Also we add a
toString() method, which is expected in all Java classes
Example Class -- Third Attempt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
import java.util.Scanner;
public class Product3 {
private String name;
private double price;
public void setProduct(String newName,
double newPrice) {
name = newName;
price = newPrice;
}
public void print() {
System.out.println(toString());
}
public void read() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the product name: ");
name = input.nextLine();
System.out.print("Enter the product price: ");
price = input.nextDouble();
input.nextLine(); // clear whitespace
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setPrice(double newPrice) {
price = newPrice;
}
public String toString() {
return "Product " + name + " @ " + price;
}
}
|
Test Class for the Example Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.util.Scanner;
public class ProductTest3 {
public static void main(String[] args) {
Product3 milk = new Product3();
Product3 bread = new Product3();
milk.setProduct("Whole milk", 4.59);
bread.read();
milk.print();
bread.print();
System.out.print("\nEnter price increase: ");
Scanner input = new Scanner(System.in);
double increase = input.nextDouble();
double milkPrice = milk.getPrice();
milk.setPrice(milkPrice + increase);
double breadPrice = bread.getPrice();
bread.setPrice(breadPrice + increase);
System.out.println(milk);
System.out.println(bread);
}
}
|
^ top
4.3.5: Method toString()
^ top
4.3.6: Summary
- OOP (object-oriented programming) provides encapsulation and information hiding for your code
- Encapsulation and information hiding allow you to change the inner workings of a class without affecting other parts of a program
- The ability to change portions of a program without affecting other parts becomes more important as programs grow larger
- All code is encapsulated in one place:
- Variables are stored in an object
- Methods are included that work with those variables
- In addition, you can hide the information of your program that is likely to change using access modifiers:
private: can only be accessed by member methods of this class
public: can be accessed any class and method
- Since variables may change over time, you declare variables
private
- For this course, use
private for all variables and public for most methods
- When you need to access private data, you use accessor and mutator methods
- An accessor method queries the object for some information without changing the state (variables) of the object
- A mutator method modifies the state (variables) of an object
- Java expects certain methods in all classes
- The reason is the Java standard libraries have code that assumes such methods are defined
- One of these methods is
toString()
- When practical, method
toString() should return all the interesting information contained in the object
Check Yourself
- What is meant by the terms "encapsulation" and "information hiding"?
- What is a member method?
- What is the difference between an accessor and a mutator method?
- Should you declare get and set methods for all instance variables? Why or why not?
- Why is the toString() method included in most classes?
- What will happen if you try to compile and execute code with the following statements?
Product milk = new Product();
System.out.println(milk);
^ top
Exercise 4.3
Take one minute to find as many problems as you can in the following class:
1
2
3
4
5
6
7
8
|
public class Product1 {
public String name;
public double price;
public void print() {
System.out.println(name + " @ " + price);
}
}
|
^ top
4.4: Constructors and Initialization
Learner Outcomes
At the end of the lesson the student will be able to:
- Write constructors with and without parameters
- Overload constructors
- Construct objects from classes with overloaded constructors
- Describe how to prevent "shadowing"
|
^ top
4.4.1: Introducing Constructors
Defining a Constructor
^ top
4.4.2: Multiple Constructors
- We can write a class with more than one constructor
- All constructors have the same name as the class, but have different parameter lists
- The technique of defining multiple constructors is known as constructor overloading
- Having multiple constructors allows us to create an object in different ways
- By allowing different ways of creating an object, we make our classes more flexible and easier to reuse
Example: Constructor with no Parameters
Example: Constructor with one Parameter
Example: Constructor with two Parameters
Implicit Default Constructors
- If the programmer does not define a constructor, then the compiler supplies an empty one like the following:
public Product() {}
- However, if the programmer defines any constructor, the compiler does not provide one
- Best practice is to always define your own no-parameter constructor
^ top
4.4.3: Yet Another Product Class
- Let us update our product class with some new constructors
- We add three constructors as shown below
Example Class -- Fourth Attempt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import java.util.Scanner;
public class Product {
private String name;
private double price;
public Product() {
name = "Unknown";
price = 0;
}
public Product(String newName) {
name = newName;
price = 0;
}
public Product(String newName, double newPrice) {
name = newName;
price = newPrice;
}
public void print() {
System.out.println(toString());
}
public void read() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the product name: ");
name = input.nextLine();
System.out.print("Enter the product price: ");
price = input.nextDouble();
input.nextLine(); // clear whitespace
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setPrice(double newPrice) {
price = newPrice;
}
public String toString() {
return "Product " + name + " @ " + price;
}
}
|
Test Class for the Example Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import java.util.Scanner;
public class ProductTest {
public static void main(String[] args) {
Product milk = new Product("Whole milk", 4.59);
Product bread = new Product("Wheat bread");
bread.setPrice(2.99);
Product cheese = new Product();
System.out.print("For cheese, ");
cheese.read();
System.out.println("\nCurrent prices:");
milk.print();
bread.print();
cheese.print();
System.out.print("\nEnter price increase: ");
Scanner input = new Scanner(System.in);
double increase = input.nextDouble();
double milkPrice = milk.getPrice();
milk.setPrice(milkPrice + increase);
double breadPrice = bread.getPrice();
bread.setPrice(breadPrice + increase);
double cheesePrice = cheese.getPrice();
cheese.setPrice(cheesePrice + increase);
System.out.println(milk);
System.out.println(bread);
System.out.println(cheese);
}
}
|
^ top
4.4.4: Creating Objects from Overloaded Constructors
- If a class has more than one constructor, our program must decide which constructor to call
- The way that C++ resolves which constructor to call is by matching the arguments to the parameter list
- Constructor matching is done based on the number and types of the parameters
- Also, the matching only works if the order is correct
- For example, assume our class has the following three constructors:
Product() { }
Product(string newName) { }
Product(string newName, double newPrice) { }
- Creating the following objects calls the indicated constructor:
Product milk; // first
Product bread("Rye Bread"); // second
Product cheese("Cheddar", 6.75); // third
- Note that names play no role in matching, only the number and type in the correct order
^ top
4.4.5: Default Values
^ top
4.4.6: Local Variables, Parameters and Shadowing
- Shadowing is when a local variable or parameter has the same name as a member variable of a class
- Local variables and parameters with same name as a member variable hide the member variable
- Any use of the variable's name will refer to the local variable or parameter
- This is the source of many an elusive bug
- You should not use the same name for a local variable or parameter and a class member variable
- Remember that a parameter is like a local variable but initialized in a special way
- Thus you should use a different name for a parameter and a member variable
- Which lines contain local shadowing in the following program and how do you correct the problem?
Example of Shadowing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class Shadowing {
private double length, width;
public Shadowing(double length, double width) {
length = length;
width = width;
}
public String toString() {
return "length: " + length + ", width: " + width;
}
public static void main(String[] args) {
Shadowing sh = new Shadowing(3, 5);
System.out.println(sh.toString());
}
}
|
What the Shadow Knows
CheckStyle to the Rescue!
^ top
4.4.7: Summary
- Constructors are used to initialize all the member variables of a class
- We can code a constructor with or without parameters
- A constructor without parameters is known as a default constructor
- We can use constructors with parameters to assign values to the member variables using the parameters
- We can write a class with more than one constructor
- If the class has more than one constructor, the constructor matching the argument list is used
- For example, assume our class has the following three constructors:
Product() { }
Product(string newName) { }
Product(string newName, double newPrice) { }
- Creating the following objects calls the indicated constructor:
Product milk; // first
Product bread("Rye Bread"); // second
Product cheese("Cheddar", 6.75); // third
- Note that names play no role in matching, only the number and type of parameters in the correct order
- Local variables are not initialized automatically
- However, instance variables are initialized automatically to 0 or null
- In addition, programmers can declare initial values explicitly
- Local variables and parameters with same name as a class variable hide the class variable
- You should not use the same name for a local variable or parameter and a class variable
Check Yourself
- What is the purpose of a constructor?
- How many constructors can you define for each class?
- When does a compiler automatically include a constructor?
- To what values does Java initialize instance variables?
- What is meant by the term "shadowing"?
- How do you avoid "shadowing"?
^ top
Exercise 4.4
Take one minute to prepare an answer the following question:
- Given a class named
Timer, which of the following is a valid declaration of a constructor:
void Timer() {}
Timer Timer() {}
Timer(Timer t) {}
public static void Timer(String args[]) {}
^ top
Wrap Up
Due Next: A3-Postal Bar Codes (3/4/09)
A4-Shape Classes (3/11/09)
^ top
Home
| Blackboard
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: March 02 2009 @11:26:04
|