Classes
Classes
Classes
Brandon Krakowsky
Classes
Classes
• Everything in Java is object‐oriented and class‐based
‐ This means you have to create at least one class to write a Java program
• A class describes an object
‐ It’s like a template for a new kind of object
‐ When you define a class, you’re defining a new data type
• To use the object, you create an instance of the class
‐ It’s a very similar concept in Python
• A class includes:
‐ Fields (instance variables) that hold the data for each object
‐ Constructors that describe how to create a new object instance of the class
‐ Methods that describe the actions the object can perform
3
11/30/2020
Defining a Class
• Here’s simple syntax for defining a sample class:
public ClassName(parameters) {
//code using parameters to set up initial state of object
}
• public means the constructor is accessible by any other program in the Java project
• ClassName has to be the same name as the class that the constructor occurs in
• The constructor parameters are a comma‐separated list of variable declarations
6
11/30/2020
return‐type methodName(parameters) {
// locally defined variables
// code using parameters
}
• If a method is to return a result, return‐type is the data type of the result
‐ You must use a return statement to exit the method with a result of the correct type
• If a method doesn’t return a result, return‐type is void
‐ This indicates that a method doesn’t return a value
‐ In this case, you don’t need to use a return statement to exit the method
9
11/30/2020
10
Dog Project
11
Dog Project
• In Eclipse, go to “File” “New” “Project”
• Click “Next”
12
11/30/2020
Dog Project
• Define the compilation/build settings
• Click “Finish”
13
Dog Class
• In Eclipse, go to “File” “New” “Class”
Provide a Package name
• ‐ Package names should not be capitalized
Click “Finish”
14
Dog Class
• The entry point of your Dog program is the main method
15
11/30/2020
16
17
18
11/30/2020
Owner Class
• Create a new class Owner
‐ This will represent a Dog owner
19
20
21
11/30/2020
22
23
24
11/30/2020
25
26
27
11/30/2020
28
29
Banking Project
30
11/30/2020
Banking Project
• In Eclipse, create a new “Banking” project
• Create 3 classes:
‐ Bank
‐ Provide the package name “banking”
‐ Make sure public static void main(String[] args) IS checked
‐ BankAccount
‐ Provide the package name “banking”
‐ Make sure public static void main(String[] args) IS NOT checked
‐ Customer
‐ Provide the package name “banking”
‐ Make sure public static void main(String[ ] args) IS NOT checked
31
Bank Class
32
BankAccount Class
33
11/30/2020
Customer Class
34
Customer Class
35
Customer Class
36
11/30/2020
BankAccount Class
37
BankAccount Class
38
BankAccount Class
39
11/30/2020
Bank Class
40
Bank Class
41
Bank Class
42
11/30/2020
Bank Class
43
Bank Class
44