Download presentation
Presentation is loading. Please wait.
1
Review of Previous Lesson
10/04/2019 Review of Previous Lesson State as many Vocabulary words and Learning Objectives that you remember from the last lesson as you can. Remember to grade yourself from
2
Object Orientated Programming Paradigm (OOP)
10/04/2019 Object Orientated Programming Paradigm (OOP) Own Classes – Exercises Simple Objects, Constructors & Overloading
3
Language Features and other Testable Topics
10/04/2019 Tested in the AP CS A Exam Notes Not tested in the AP CS A Exam, but potentially relevant/useful Variables private instance variables: visibility (private) Methods visibility (public, private), static, non-static, method signatures, overloading, parameter passing 9 Constructors 12 Classes new, visibility (public), Design/create/modify class. 13
4
Language Features and other Testable Topics
10/04/2019 Notes: 9. The main method and command-line arguments are not included in the subset. In free-response questions, students are not expected to invoke programs. In the AP Computer Science Labs, program invocation with main may occur, but the main method will be kept very simple. 12. Students are expected to implement constructors that initialize all instance variables. 13. Students are expected to write interfaces or class declarations when given a general description of the interface or class.
5
Object Orientated Programming (OOP)
10/04/2019 Object Orientated Programming (OOP) Look around you at the ‘Real World’ and the things that are in it. What word from the title above can you use to describe what you see? Objects OOP is a way of organizing program logic so it matches the thinking style of our object-oriented brains.
6
10/04/2019 Write your own programs: Write your own programs from “scratch”. Of course you should use previous programs for reference, but write your code from “scratch” (do not copy and paste).
7
Class Reminder 10/04/2019 ? A template/blueprint/instructions/factory for objects. Is the data type of any objects created from it (or sub-classes – see later). A set of instructions that describe how an object will behave (methods – mini programs) and what characteristics (states – see next slide) it must have. e.g. Many classes are pre-defined in Java (standard classes). A programmer can invent new classes to meet the particular needs of a program. Constructor: Every class has at least one constructor method which, when called, creates/initialises/sets up an object. May or may not require certain “parameters” to be passed to it. e.g. size, colour, etc….
8
Objects: Reminder 10/04/2019 ? Are the instances (results) of a class created by following the description contained in its class (or sub-classes – see later). Has 3 characteristics: State/Properties/Data Members/Instance Variables: Data (values) each object (instance of a class) has as part of itself which may change over the course of the object’s ‘lifetime’. All objects of the same class have the same types of data although the values of the data will be different from object to object. e.g. animal: its length, what it eats, number of legs, etc… bank account: balance, interest rate, daily withdrawal limit, etc… pen: name is Reynolds, colour is white etc. Behaviour/Methods/Mini Programs: Functionality of an object (it can do things and can have things done to it) such as: animal: the sound it produces, bank account: deposit, withdraw etc. pen: writing Identity: Typically implemented via a unique ID. The value of the ID is not visible to the external user. Is used internally by the JVM to identify each object uniquely. members What states and behaviours are required are set by the class (or classes - see later) it comes from. After a program stops running, any created objects no longer exist. Objects are created at and exist during Run Time only.
9
Object name / reference variable name
Objects 10/04/2019 If you visit the name of the object’s (reference variable name) memory location, unlike the primitive type, you will find a memory address pointing to another location and not the values of variables in object. This memory address points to a location where the details of object and values of variables inside it reside (in an area of memory called “The Heap” – see later). Analogy Object name / reference variable name (contact name) …….. (friend)
10
Object name / reference variable name
What is the object? 10/04/2019 Your friend does not have to use your ‘real name’ in their contact list (they could choose anything). This ‘name’ and ‘you’ are not the same things. Analogy Object name / reference variable name (contact name) …….. (friend) There is no actual object named ‘variable1’, only a reference variable of that name. A Java variable never contains an object! So really we should say: "The object referred to by the variable ‘variable1’.“ rather than: "The object variable1... " In fact, every object actually does have a unique ID, which could be said to be the actual object, but this unique ID is only internally visible within the JVM, not to the programs that create and use them.
11
To create/instantiate/construct an object:
10/04/2019 Reminder ? Standard Java formatting dictates that it begins with a capital letter and for multiple words use to begin each word (no spaces are allowed so this makes them more readable). Some constructors may require certain information called “actual” parameters written inside the brackets in a specific order separated by ,. The left side can be written separately (Student student1;) & declares that this variable may refer to an object of a specific class. The object does not exist unit the "new" is executed. Reference Variable Name Can be anything the programmer chooses but standard Java formatting dictates that they follow the same rules as variable names: begin with a lower case letter and for multiple words use a capital from the 2nd word to begin each word. Must have the same name as the Class Name. Can be considered to be a special type of method. Creates/initialises a newly created object.
12
Dot Notation (non-static methods)
Reminder 10/04/2019 ? The way variables and methods are accessed/called/invoked. Non-Static methods: objectReference.memberOfObject objectReference.variableName objectReference.methodName() If parameters are required, they should listed here according to the method’s signature.
13
Reminder 10/04/2019 Types of Constructors ?
14
? Default constructor Reminder JAVAC 10/04/2019
If you do not implement any constructor in your class, Javac inserts a default constructor into your code on your behalf. You will not find it in your source code (the java file) as it would be inserted into the code during compilation and exists in .class file. This means that class will still have a constructor, it is just that the programmer didn’t write it. public class MyClass { public static void main (String args[]) { MyClass obj = new MyClass(); } …. public class MyClass { MyClass() { } public static void main (String args[]) { MyClass obj = new MyClass(); …. JAVAC
15
Implementation techniques
10/04/2019 ? As you know the first method to run is the static method named main() and there should be only one method named main() in an application. In small applications, main() might do by itself all the computation that needs to be done. In larger applications, we should use OOP: main() will only directly deal with user interaction and any other I/O. Here, main() will create objects and use their methods to do the real work.
16
Writing methods in the same class as the main() method
10/04/2019 Writing methods in the same class as the main() method ? This does not allow methods to be used by other programs easily as the class holds a main() method. So a programmer would have to copy the class code and remove the main () method.
17
Writing a class with only the main method and writing all other methods in at least one separate class. 10/04/2019 ? AP CS seems to mainly use the name ‘Test’. For the reasons stated on the previous slide it is standard OOP to: Create one class (sometimes referred to as the ‘Driver/Test/Tester’ class) that serves no other purpose than to contain the main() method, which is used to start things running. When JAVAC compiles a program with multiple classes, it outputs separate files of bytecodes, one for each class. As before the main() method calls static methods (but they are now in another class) and these static methods do the real work of the program. We will leave Java to choose the default accessibility of other classes. If you want more than one class to be public you must put each class in a separate file and save each separately. Javac does not allow more than one class to be public in the same file as public classes must have the same name as the public class.
18
Hello 1 Write a definition of a class HelloObject which includes:
10/04/2019 Hello 1 Write a definition of a class HelloObject which includes: A single no arg method named speak() which displays the message “Hello from an object!”. No instance variables. No programmer defined constructor. Write a class named HelloTester with a single main() method which constructs a HelloObject and then invokes that object's speak() method. Continued on the next slide.
19
Syntax of a Class Definition
10/04/2019 Syntax of a Class Definition modifiers class ClassName { // Description of the instance variables // Description of the constructors // Description of the methods } For now, replace modifiers with public in the class that contains main and don't include it in other classes in the same file (default accessibility). If you want more than one class to be public you must put each class in a separate file and save each separately. Javac does not allow more than one class to be public in the same file as public classes must have the same name as the source file. Separating the class into sections is done for clarity, it is not a rule of the language.
20
Non-static Method Definition Syntax
10/04/2019 Non-static Method Definition Syntax modifier returnType methodName( parameterList ) { // Java statements return returnValue; } For now, use the public modifier. The returnType is the type of value that the method hands back to the caller of the method. Your methods can return values just as do methods from library classes. The return statement is used to hand back a value to the caller. If you want a method that just does something, but does not return a value to the caller, use a return type of void and do not use a return value with the return statement (actually Javac does not mind return in void methods, but I personally see little reason to). If you want a static method then add static after the modifier (if no modifier then just start with static).
21
10/04/2019 Hello 1 class HelloObject { // 2a. The class definition is used to make the object public void speak() { // 2b. A speak() method is included in the object. System.out.println("Hello from an object!"); // 3a. The speak() method of the object prints a message on the screen. // 3b. The method stops and program returns control to the caller. }
22
10/04/2019 Hello 1
23
Hello 1 Answer the following questions in your comments: 10/04/2019
What is the difference between a class and an object? Does each object require a main() method? Name the classes defined in your code. Name the methods defined in each class. Where would you find the definition of a HelloObject? Can you activate the speak() method without creating an object? Does the class HelloObject have a constructor? A default constructor does no work. Is this correct? Can a class description be used to create more than one object?
24
Hello 1 Answer the following questions in your comments: 10/04/2019
What is the difference between a class and an object? A class is a description of a possible object. An object is a unique instance of a class. Does each object require a main() method? No. You need only one main() method for the Java virtual machine to use in starting your program. Name the classes defined in your code. HelloObject and HelloTester Name the methods defined in each class. The HelloObject class has a speak() method. The HelloTester class has a main() method. Where would you find the definition of a HelloObject? In the file of bytecodes, HelloObject.class. Can you activate the speak() method without creating an object? No because it is not a static method.
25
Hello 1 Answer the following questions in your comments: 10/04/2019
Does the class HelloObject have a constructor? Yes. To construct an object, there must be a constructor. A default constructor does no work. Is this correct? No. The default constructor does a great deal of work behind the scenes. It works with the JVM to find main memory for the object, sets up that memory as an object, puts in any variables and methods specified in the class definition, and returns an object reference (address of the object). Can a class description be used to create more than one object? Yes. A big program might need thousands of objects as it runs, but might have only a few dozen class descriptions. The code could look like this: HelloObject hello1 = new HelloObject(); HelloObject hello2 = new HelloObject(); hello1.speak(); hello2.speak(); The Heap hello1 reference HelloObject hello2 reference HelloObject But both objects will do the same thing when their speak() method is called.
26
Hello 1 Please add code to the main method to create multiple objects
10/04/2019 Hello 1 Please add code to the main method to create multiple objects (at least one more object).
27
10/04/2019 Hello 2 Extend the previous version so that different objects printed different things, meaning that each HelloObject has its own message. Where should this message be kept? Continued on the next slide.
28
? Instance Variables: Reminder 10/04/2019 Members of a class.
Data (values) each object (instance of a class) has as part of itself which may change over the course of the object’s ‘lifetime’. All objects of the same class have the same types of data although the values of the data will be different from object to object. e.g. animal: its length, what it eats, number of legs, etc… bank account: balance, interest rate, daily withdrawal limit, etc… pen: name is Reynolds, colour is white etc. set by the class (or classes - see later) it comes from.
29
private Instance variables
10/04/2019 ? private The private modifier provides “Careful Access Control”, as it disallows any unapproved access (e.g. ClassName.instanceVariableName) / changes (e.g. ClassName.instanceVariableName = …) to instance variables from outside this class (only permitted access/changes through any approved methods within its class will be allowed). Instance Declared outside any method declarations. Their values are instance/Object specific and are not shared among instances/objects. Typically instance variables are private or protected. Protected can be chosen when child classes are anticipated, to allow direct changes to instance variables from sub classes. However, protected also allows direct changes from classes within the same package (i.e. the main () method in the ‘Test’ class within the same file or folder). Subsequently, some programmers consider this to be a controversial decision by the designers of the Java language. The AP CS syllabus only obliges you to use ‘private’ access to instance variables to force changes to be made only through any approved methods from outside their class.
30
Hello 2 The message should be kept in an instance variable.
10/04/2019 Hello 2 The message should be kept in an instance variable. What will be needed to set the instance variable above to the message required when the object is constructed. What does its name have to be? Continued on the next slide.
31
Reminder 10/04/2019 Parameters ? Variables/literals (fixed values) passed between (sent to and / or from) methods/constructors. Passing = sending to or from Necessary if the called method or constructor needs a local variable from the calling method.
32
Reminder 10/04/2019 Types of Constructors ? /
33
Parameterized Constructor
Reminder 10/04/2019 Parameterized Constructor ? Constructor requiring arguments (“actual” parameters) to be passed to it. Formal parameters Declarations in the constructor’s (or method's) header. Actual parameters Values/Variables passed at the point of invocation (when called). While the phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".
34
Hello 2 The message should be kept in an instance variable.
10/04/2019 Hello 2 The message should be kept in an instance variable. There will be a need for a parameterized constructor to set the instance variable to the message sent to it. What will we have to do to the speak() method so that it uses the instance variable mentioned above? What will we need to do to the way a HelloObject is constructed in the main() method, so that the message can be ‘passed’? Create at least 4 different HelloObjects with different messages. Continued on the next slide.
35
To create/instantiate/construct an object:
10/04/2019 Reminder Standard Java formatting dictates that it begins with a capital letter and for multiple words use to begin each word (no spaces are allowed so this makes them more readable). ? Some constructors may require certain information called “actual” parameters written inside the brackets in a specific order separated by ,. The left side can be written separately (Student student1;) & declares that this variable may refer to an object of a specific class. The object does not exist unit the "new" is executed. Can be anything the programmer chooses but standard Java formatting dictates that they follow the same rules as variable names: begin with a lower case letter and for multiple words use a capital from the 2nd word to begin each word. Must have the same name as the Class Name. Can be considered to be a special type of method. Creates/initialises a newly created object.
36
Hello 2 The message should be kept in an instance variable.
10/04/2019 Hello 2 The message should be kept in an instance variable. There will be a need for a parameterized constructor to set the instance variable to the message sent to it. A modified speak() method so that it uses an instance variable. Modify the way a HelloObject is constructed in the main() method by passing it a message. Create at least 4 different HelloObjects with different messages. Continued on the next slide.
37
Constructor Definition Syntax
10/04/2019 Constructor Definition Syntax public className( parameterList ) { Statements involving the instance variables of the class and the parameters in the parameterList. Typically a constructor initialises the instance variables. }
38
Hello 2 10/04/2019 The name for the constructor's parameter is not very meaningful. What can be done about this? See the next 3 slides for a discussion about this point.
39
10/04/2019 Dante asks why data cannot go into ‘greeting’ directly? Why does it have to be stored in a constructor parameter variable like st 1st? When you write down something somebody has told you, where is it between somebody telling you and it ending up on the paper? Answer: Your brain. The header can be thought of as the brain. The constructor needs this information before it can start constructing an object. The header is the setup part, the constructor (or method) has not started until after {. Before starting to construct an object, the instance variable ‘greeting’ does not exist.
40
Analogy for the next slide:
10/04/2019 Analogy for the next slide: Your actual cell number and the cell number your friend has in their contact list have to be the same before they can call you. …….. (friend) But your actual name and the name your friend used for you in their contact list could be: Completely different as they used a meaningless name. The same. Or similar as they used a different but still meaningful name. (e.g. nickname, English name when your real name is your Chinese name, etc…).
41
(as on the previous slide) constructorParaName is .
10/04/2019 this The use of ‘this’ as shown here is actually not included in AP CS and is positively discouraged: Students are not required to know the idiom "this.var = var”, where var is both the name of an instance variable and a local parameter variable. I am including it here as it is common usage, and considered best practice, to use meaningful names for variables; that is to use the same name for instance and parameter variables. Therefore AP CS is likely to use constructor parameter names like: (as on the previous slide) constructorParaName is This idea of ‘aGreeting’ seems to be a good way of using a meaningful variable name whilst still being different to the instance variable name. (as on the previous slide) Must use this.instanceVarName to distinguish it from the constructorParaName. meaningful not meaningful OR OR class HelloObject { private String greeting; public HelloObject( String st ) { greeting = st; } class HelloObject { private String greeting; public HelloObject( String greeting ) { this.greeting = greeting; } class HelloObject { private String greeting; public HelloObject( String aGreeting ) { greeting = aGreeting; } meaningful different same different this.
42
Hello 2 10/04/2019 Obviously you don’t have to use these specific messages, please free to write your own.
43
Hello 2 Answer the following questions in your comments: 10/04/2019
Name the parameter/s of the constructor. What are the naming conventions for a constructor’s parameters? Discuss the issues surrounding these conventions. Can a parameter be an object reference? Can a parameter be a primitive data type? What does this program print on the monitor when it is run? How many objects exist just before this program stops running? Are there several HelloObject objects created in the main() method? Can parameters have the same names as variables, methods or classes? How many constructors does the HelloObject class have?
44
Hello 2 Answer the following questions in your comments: 10/04/2019
Name the parameter/s of the constructor. A reference to a string (st). What are the naming conventions for a constructor’s parameters? Discuss the issues surrounding these conventions. Use the same names as any Instance Variables to be set. Must use this.InstanceVariableName to distinguish them from the constructor’s parameter names. Not used in AP CS. Use completely different names to any Instance Variables to be set. Likely that parameter names are not meaningful. Use similar names to any Instance Variables to be set (e.g. aGreeting). No need to use this and variable names can still be meaningful. Not used widely in AP CS. Can a parameter be an object reference? Yes. Can a parameter be a primitive data type?
45
Hello 2 Answer the following questions in your comments: 10/04/2019
What does this program print on the monitor when it is run? The strings located at the references passed to each object. How many objects exist just before this program stops running? If all messages passed are unique: the number of HelloObjects created in the main method * 2: The String objects located at the references which were passed to each object. If some objects were passed the same message then this would be counted as one String object as each of object’s instance variable with the same message would point to the same String object. The HelloObjects. Are there several HelloObject objects created in the main() method? Yes. Can parameters have the same names as variables, methods or classes? Yes, but we must use this.instanceVariableReferenceName to distinguish them. How many constructors does the HelloObject class have? 1: When your code defines a constructor for a class, a default constructor is no longer automatically supplied by the compiler.
46
10/04/2019 Hello 3 Extend the previous version so that if no message is given (like ‘Hello 1’), some sort of default message is printed. As we now have a programmer written constructor, javac will no longer supply a default. So if we write the following line from Hello 1, in Hello 2 : HelloObject anObject = new HelloObject(); // As in Hello 1. Javac will complain as the parametrised constructor we have in Hello 2 requires a parameter and we have not given one. How can we do this? Continued on the next slide.
47
Reminder 10/04/2019 Types of Constructors ? /
48
? no-arg Constructor Constructor with no arguments/parameters.
10/04/2019 ? Constructor with no arguments/parameters. Creation/Instantiation is the same as with the default constructor, however the body can have any code unlike default constructor where the body of the constructor is empty. The default and no-arg constructor are not the same, even if you write public Demo() { } in your class Demo it cannot be called the default constructor since you have written the code of it.
49
10/04/2019 If we write two constructors, won’t Java complain and how will it know which one to use?
50
Reminder 10/04/2019 Signature In the Java programming language, a signature is the method/constructor name and the number, type and order of its parameters. methodOrConstructorName(parameters) {...}; e.g. doSomething(int y, int x); doSomething(int x, int y); doSomething(double x, int y); doSomething(int x, double y); ? Same signature (variable names not important, only their types). Different and distinct signatures.
51
10/04/2019 Can we just write a blank ‘no-arg’ constructor just like a ‘default’ constructor? A blank ‘no-arg’ constructor similar to a ‘default’ constructor is technically possible but …. Try it if you are not sure – see next slide.
52
Hello 3 10/04/2019
53
10/04/2019 Can we just write a blank ‘no-arg’ constructor just like a ‘default’ constructor? A blank ‘no-arg’ constructor similar to a ‘default’ constructor is technically possible but, as the speak() method has now be written to use the instance variable ‘greeting’, nothing (‘null’) will be printed. Therefore the ‘no-arg’ constructor will have to set the instance variable ‘greeting’ to some chosen default.
54
Hello 3 10/04/2019
55
Hello 3 Answer the following question in your comments: 10/04/2019
How does the JVM ‘know’ which constructor to use?
56
Hello 3 Answer the following question in your comments: 10/04/2019
How does the JVM ‘know’ which constructor to use? The JVM looks at the parameters being passed to the and compares this with the signature of each constructor. If a match is found then that constructor is used. Signature: name of constructor/method number, data types and order of parameters
57
10/04/2019 Hello 4 Extend the previous version so that if an occasion (e.g. “birthday” or “anniversary”) and a number is given, “Happy ” + num + “th ” + occasion + “!” is displayed (e.g. “Happy 10th birthday!”). How can we do this? Continued on the next slide.
58
10/04/2019 Hello 4 Extend the previous version so that if an occasion (e.g. “birthday” or “anniversary”) and a number is given, “Happy ” + num + “th ” + occasion + “!” is displayed (e.g. “Happy 10th birthday!”). We will write a second parameterised constructor. How will Java know which one to use? Continued on the next slide.
59
Reminder 10/04/2019 Signature In the Java programming language, a signature is the method/constructor name and the number, type and order of its parameters. methodOrConstructorName(parameters) {...}; e.g. doSomething(int y, int x); doSomething(int x, int y); doSomething(double x, int y); doSomething(int x, double y); ? Same signature (variable names not important, only their types). Different and distinct signatures.
60
Hello 4 10/04/2019
61
Hello 4 10/04/2019
62
10/04/2019 Overloading Overloading is when there are two or more constructors/methods of a class with the same name (constructors must have the same name as the class anyway) but have different parameter lists. When a constructor/method is called, the correct constructor/method is picked by matching the actual parameters in the call to the formal parameter lists of the methods (also known as its signature). The + operator is the only Java operator that is internally overloaded.
63
Hello 4 Answer in your comments: 10/04/2019
What do we call this when we have 2 or more constructors (or methods) with the same name in the same class?
64
10/04/2019 Hello 4 What do we call this when we have 2 or more constructors (or methods) with the same name in the same class? Overloading is when there are two or more constructors/methods of a class with the same name (constructors must have the same name as the class name anyway) but have different parameter lists. When a constructor/method is called, the correct constructor/method is picked by matching the actual parameters in the call to the formal parameter lists of the methods (also known as its signature). The + operator is the only Java operator that is internally overloaded.
65
4/10/2019 Grade yourself Grade yourself on the vocabulary and learning objectives of the presentation.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.