OOP with Java · quiz revision · 4 slide decks, 145 slides

Java Quiz Revision

Chapter 1 (intro to OOP, getting started with Java, numerical data) and Chapter 2 (programmer-defined classes, this, overloading). Every slide is covered, including the ones that were only pictures and diagrams.

colour code: key term / definition exam trap syntax / code example value rule to memorise

✎ Select any text to add your own highlights. They're saved and only you can see them.

Chapter 1 · Part 1

Intro to Object-Oriented Programming & Software Development

by the end you should be able to…
1.1

History of programming (paradigm)

learnt›
  • An algorithm = a step-by-step process.
  • A computer program = a step-by-step set of instructions for a computer.
  • Every computer program is an algorithm. Algorithms have a long history in science, technology, engineering & math.
  • Early computers: far less complex, smaller memories, simpler programs, usually executed only one program at a time.
  • Modern computers: smaller but far more complex, can execute many programs at the same time.

how we got to OOP

Algorithmstep-by-step process
→
Computer programinstructions for a computer
→
Early computerssimple · 1 program at a time
→
Modern computerscomplex · many programs
→
OOPobjects manage the complexity
1.2

What is object-oriented programming?

learnt›
  • Computer scientists introduced objects and OOP to help manage the growing complexity of modern computers.
  • Prof. Alan Kay is one of the fathers of OOP. He named it, with colleagues at PARC, back in 1966.
  • OOP is centred on creating objects rather than procedures/functions.
  • Objects are a melding of data + the procedures that manipulate that data.
  • Wikipedia definition: OOP is a programming paradigm based on "objects", which are data structures that contain data (fields) and code (procedures).
  • In OO programming, programs are designed by making them out of objects that interact with one another.

anatomy of an object

Dataaka fields → attributes
+
Procedures / functionsaka code → methods
=
OBJECT
  • An object is anything that can be represented by data.
  • It can be physical or just an abstract idea:
    • airplane → physical object that can be manipulated by a computer
    • bank transaction → an object that is not physical
  • To a computer, an object is simply something that can be represented by data in the computer's memory and manipulated by computer programs.
1.3

Classes & objects

learnt›
  • Object-oriented programs use objects.
  • An object is a thing, both tangible and intangible: Account, Vehicle, Employee…
  • To create an object in a program we must first provide a definition of how it behaves and what information it maintains. That definition is a class.
  • An object is called an instance of a class.

the cookie-cutter picture

Class= the cookie cutter (template)
→
object
object
object

one class (cutter) can stamp out many objects (cookies) → "an object is an instance of a class"

1.4

Drawing classes & objects (UML)

learnt›
  • The notation is based on the industry standard UML = Unified Modeling Language.
  • Class → a rectangle with the class name inside (e.g. Account, Motorcycle).
  • Object → a rectangle with the underlined object name inside (e.g. SV198).
  • Object with class name → <Object Name> : <Class Name>, shows which class the object is an instance of, e.g. SV198 : BankAccount.

the three icons

Account
class · plain name
SV198
object · underlined
SV198 : BankAccount
object + its class
1.5

Messages & methods

learnt›
  • To make a class or object do a task, we send a message to it.
  • You can only send a message to classes/objects that understand it: they must have a matching method to handle it.
  • Method defined for a class → class method. Method defined for an object → instance method.
  • A value passed with a message = an argument of the message.

three message diagrams from the slides

deposit 250.00message + argument
→
SV198 : BankAccount

① message deposit with argument 250.00 is sent to object SV198 (instance method, nothing returned)

getCurrentBalance()
→
SV198 : BankAccount
→
current balancereturned to sender

② ask for the current balance of this particular account → the balance is returned

getMaximumSpeed()
→
MobileRobot
→
maximum speedreturned

③ class method: sent to the class itself (not underlined), returns the max possible speed for all MobileRobot objects

1.6

Class vs instance data values

learnt›
  • An object is made of data values + methods.
  • Instance data value → info specific to each individual instance. e.g. every BankAccount keeps its own current balance.
  • Class data value → info shared by all instances or aggregate info about the instances.
    • minimum balance → shared by all Account objects
    • average balance of all BankAccounts → aggregate information
  • There is ONE copy of a class data value for the whole class, shared by all instances.

sample class & instance data values

  • BankAccount
    minimum balance100.00
    • SV129 : BankAccount
      current balance908.55
    • SV098 : BankAccount
      current balance1304.98
    • SV211 : BankAccount
      current balance354.00

the dashed lines = instance-of relationship · one shared copy of minimum balance in the class · all 3 objects have the same instance data value (current balance) but different amounts

no class icon drawn?

SV129 : BankAccount
minimum balance100.00current balance908.55
ruleWhen the class icon is not shown, put the class data value inside the object icon itself.
1.7

Inheritance

learnt›
  • Inheritance = a mechanism to design two or more entities that are different but share many common features.
  • Common features are defined in the superclass. Classes that inherit them are subclasses.
  • superclass = ancestor · subclass = descendant
  • In the diagrams the arrow (hollow triangle) points UP to the superclass.

sample inheritance

  • Account
    • Checking
    • Savings

inheritance hierarchy

  • Student
    • Graduate
      • Masters
      • Doctoral
      • Law
    • Undergrad
      • Commuting
      • Resident
1.8

Software engineering & the life cycle

learnt›
  • Like building a skyscraper, complex software needs a disciplined approach.
  • Software engineering = applying a systematic and disciplined approach to the development, testing and maintenance of a program.
  • Software life cycle = the sequence of stages from conception to operation of a program. It has 5 stages:

the 5 stages, in order

1 · Analysis
→
2 · Design
→
3 · Coding
→
4 · Testing
→
5 · Operation & Maintenance

mnemonic: A D C T O → "A Dog Can Take Orders"

1.9

5 advantages of OOP + OOP languages

learnt›
#AdvantageWhy
1Improved software-development productivitymodular (separation of duties), extensible (objects extended with new attributes & behaviours), reused within and across applications
2Improved software maintainabilityeasier to maintain; modular design means part of the system can be updated without large-scale changes
3Faster developmentreuse → faster development; rich libraries of objects; project code reusable in future projects
4Lower cost of developmentreuse lowers cost; more effort goes into OO analysis & design, which lowers the overall cost
5Higher-quality softwarefaster + cheaper → more time & resources for verification (quality still depends on team experience)
  • Two popular OOP languages: Java and C++.
  • Other OOP languages: Objective C, Perl, Python, JavaScript, Simula, Modula, Ada, Smalltalk.
✎

Quick self-test · tap to flip

learnt›
Chapter 1 · Part 2

Getting Started with Java & Numerical Data

by the end you should be able to…
2.1

Identifiers & naming convention

learnt›
  • A Java identifier = a sequence of letters, digits, underscores (_) and dollar signs ($), with the first character a non-digit.
  • Used to name a class, object, method, and others.
VALIDINVALIDwhy invalid
MyFirstApplication45678starts with a digit
FunTimeSample Programcontains a space
DEFAULT_VALUEhello,therecomma not allowed

standard naming convention

Robotclass name → Capital first
robotobject name → small first

multiple words → capitalise the first letter of every word, except the first word if it's an object name

MyMainWindowclass
myMainWindowobject (NOT mymainwindow)
lecturer's question: "not necessary? common ways?"It's a convention, so the compiler won't complain if you break it. But it's the standard, common way every Java programmer follows, so use it.
2.2

Declaration vs creation (objects in memory)

learnt›
java
Customer customer;            // 1. declaration
customer = new Customer( );   // 2. creation

what happens in memory

1
customer
identifier customer is declared and space is allocated in memory
2
customer
→
: Customer
a Customer object is created and customer is set to refer to it
  • Combine both into one statement: Student john = new Student(); instead of Student john; + john = new Student();

name vs objects: calling new twice

java
Customer customer;
customer = new Customer( );   // first object
customer = new Customer( );   // second object
customer
→
: Customer
2nd new · now referenced
: Customer
1st new
no variable points here any morethis object can't be reached

the second new makes customer point to the new object → reference to the first Customer object is lost

2.3

Sending messages & program components

learnt›
  • Syntax: <object>.<method>(<arguments>); e.g. account.deposit(200.0); · student.setName("john"); · car1.startEngine();
  • A Java program is made of 3 components: comments, import statements, class declarations.
java
/* The program is
   expected to print Java */          // comment
public class Main{                    // class
  String attribute;
  public void display() {             // method
    System.out.println(attribute);}
  public static void main(String[] args) {
    Main obj = new Main();
    // obj.attribute = "Hello"; This line is commented
    obj.attribute = "Java";
    obj.display();
  }
}
Java
2.4

Comments

learnt›
TypeMarkersUse
Multiline/* … */comment across several lines
Single line// …everything after // on that line
javadoc/** … */documentation comment, e.g. describing a class ("This class provides basic clock functions…")
matching markers
/*
/*
/*
This is a comment
*/
*/     <-- Error!
exam trap

Comments do not nest. The first */ closes the comment, so the inner /* markers are just part of the comment text.

The leftover */ gives "Error: No matching beginning marker."

2.5

Import statements & standard classes

learnt›

import syntax

importkeyword
<package name>package that contains the class
. 
<class name>class to import (* = all)
; 

e.g. dorm.Resident; · import javax.swing.JFrame; · import java.util.*; · import com.drcaffeine.simplegui.*;

java
import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    String S;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a string");
    S = in.nextLine();
    System.out.println("You enter a string " + S);
  }}
Enter a string Jojo You enter a string Jojo
  • Why use standard classes? Don't reinvent the wheel. If existing objects satisfy our needs, use them.
  • Learning to use standard classes is the first step toward mastering OOP; learn existing classes before defining your own.
Standard classPackageUsed for
Scannerjava.utilkeyboard input
Stringjava.langtext (auto-imported)
Datejava.utilcurrent date & time
SimpleDateFormatjava.textformatting dates
2.6

Standard output: print vs println

learnt›
  • System.out is an instance of the PrintStream class, a simple way to show results on the console window (its look depends on the Java tool you use).
  • print → keeps printing from the end of the current output (same line).
  • println → skips to the next line after printing its argument.
print
System.out.print("How do you do? ");
System.out.print("My name is ");
System.out.print("Jon Java. ");
How do you do? My name is Jon Java.
println
System.out.println("How do you do? ");
System.out.println("My name is ");
System.out.println("Jon Java. ");
How do you do? My name is Jon Java.
2.7

String: an object with methods

learnt›

String is an object

java
String name;                  // 1
name = new String("Jon Java"); // 2
name
→
: String
Jon Java

1 = identifier name declared, space allocated · 2 = String object created, name refers to it

Indexing: the position (index) of the first character is 0.

charAt(index)

0E1x2p3r4e5s6s7o

String a = "Expresso"; → a.charAt(3) gives r · a.length() gives 8 (last index = length − 1)

MethodReturnsExamples
str.length()number of characters in str"programming" → 11 · "Hello" → 5 · "Java" → 4 · "" (empty) → 0 · " " (one space) → 1
str.indexOf(substr)first position where substr occurs; −1 if not found; case-sensitive"programming".indexOf("gram") → 3
+ (concatenation)joins stringssee below

str = "I Love Java and Java loves me.";

str.indexOf("J")7first J
str.indexOf("love")21lowercase "love" is inside "loves", not "Love"
str.indexOf("ove")3"ove" is found in "Love"
str.indexOf("Me")−1"Me" not found (case-sensitive, text has "me")
str1 = "Jon"; str2 = "Java";Result
str1 + str2"JonJava" (no space added!)
str1 + " " + str2"Jon Java"
str2 + ", " + str1"Java, Jon"
"Are you " + str1 + "?""Are you Jon?"
2.8

Date & SimpleDateFormat

learnt›
Date
import java.util.*;
//import java.util.Date;
//import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Date today;
    today = new Date( );
    System.out.println(today);
  }
}
Mon Sep 14 08:59:17 UTC 2026
SimpleDateFormat
import java.util.Date;
import java.text.SimpleDateFormat;
...
Date today = new Date( );
SimpleDateFormat sdf1, sdf2;
sdf1 = new SimpleDateFormat("MM/dd/yy");
sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
String a = sdf1.format(today);
String b = sdf2.format(today);
System.out.println(a + "\n" + b);
09/14/26 September 14, 2026
  • java.util.* imports all classes in java.util (so both Date and Scanner).
  • MM = month number · MMMM = full month name · dd = day · yy / yyyy = 2- / 4-digit year.
lecturer's question: "format() belongs to SimpleDateFormat?"Yes. You call it on a SimpleDateFormat object (sdf1.format(today)) and it returns the date as a String.
2.9

Standard input with Scanner

learnt›
  • A Scanner object reads data from standard input System.in (the keyboard).
  • First associate a Scanner with System.in, then read.

input flow

import java.util.Scanner;
→
Scanner in = new Scanner(System.in);
→
name = in.nextLine();
java
import java.util.Scanner;
public class Main {
  public static void main(String args[]) {
    String name;
    Scanner in = new Scanner(System.in);
    name = in.nextLine();
    System.out.println("Hello there, " + name);
    System.out.println("Welcome to Java");
  }
}
2.10

Numerical data types *** in slides

learnt›
  • Before adding x + y we must declare their data type: int x, y; or int x; int y;
  • 6 numerical data types: byte, short, int, long (integers) and float, double (real numbers).
  • Declare several at once: int i, j, k; · float numberOne, numberTwo; · long bigInteger; · double bigNumber;
  • Initialise while declaring: int count = 10, height = 34;
TypeContentDefaultMinimumMaximum
byteInteger0−128127
shortInteger0−3276832767
intInteger0−21474836482147483647
longInteger0−92233720368547758089223372036854775807
floatReal0.0−3.40282347E+383.40282347E+38
doubleReal0.0−1.79769313486231570E+3081.79769313486231570E+308

precision ladder (low → high)

byte
→
short
→
int
→
long
→
float
→
double
long literal
long a = 323456789098765L;
System.out.println(a);
323456789098765
lecturer's question: "E+38 is?"

E+38 means × 1038. So 3.40282347E+38 = 340,282,347 followed by 30 zeros.

A big whole number literal needs L at the end to be a long.

2.11

Assignment & arithmetic operators

learnt›
  • Assignment syntax: <variable> = <expression>; e.g. sum = firstNumber + secondNumber; · avg = (one + two + three) / 3.0;
OperationOperatorExampleValue (x = 10, y = 7, z = 2.5)
Addition+x + y17
Subtraction-x - y3
Multiplication*x * y70
Division/x / y
x / z
1 (not 1.429!)
4.0
Modulo (remainder)%x % y3
exam trap: integer divisionint / int is integer division: the fractional part is truncated (10 / 7 = 1). If one operand is real (x / z) you get a real answer (4.0). Use a DecimalFormat object to format numerical output.

The modulo operator returns the remainder of a division. It works with real numbers too, but is mostly used with integers.

ModuloResult
23 % 53
23 % 2523
16 % 20
rememberIf the left number is smaller than the right one, the remainder is the left number itself: 23 % 25 = 23. A result of 0 means it divides exactly (16 is even).
2.12

Precedence rules

learnt›
  • x + 3 * y → x is added to 3*y (multiply first).
  • Higher precedence is evaluated first. Same precedence → left to right (for most operators).

evaluation order: high → low

1 · Subexpression ( )innermost first · same level → left to right
→
2 · Unary operator - +unary minus / plus
→
3 · Multiplicative * / %left to right
→
4 · Additive + -evaluated last · left to right
2.13

Type casting (implicit & explicit)

learnt›
  • Mixed expression = operands of different types. If x is float and y is int, x * y is a float.
  • Promotion rules: the expression's type = the type of the operand with the highest precision.

casting decision flow

int value → double variablelow → high precision
→
✓ implicit promotionautomatic · double x = 3 + 5; → 8.0
double value → int variablehigh → low precision
→
✗ demotion not allowedcompile error · int x = 3.5;
want to choose the type yourself?
→
explicit cast(float) x / 3 · (int) (x / y * 3.0)

Implicit: double x = 3 + 5; → 3 + 5 is int 8, promoted to 8.0 (double) before being assigned.

int x = 3.5; → error: a higher precision value cannot be assigned to a lower precision variable.

Explicit: prefix the operand with the type, syntax ( <data type> ) <expression>

  • (float) x / 3 → cast x to float, then divide by 3
  • (int) (x / y * 3.0) → cast the result of the whole expression to int
explicit cast example
int x = 10;
float y;
y = (float) x / 3;
System.out.println(y);
3.3333333
2.14

Constants *** in slides

learnt›
  • A variable's value can change. If the value must remain the same, use a constant (a named constant).
  • The reserved word final declares a constant: final double PI = 3.14159; · final int MONTH_IN_YEAR = 12;
  • Naming style for constants: ALL_CAPS with underscores.
with final
final int x = 10;
x = 20;          // not allowed
int y;
y = x / 5;
System.out.println(y);
error: cannot assign a value to final variable x
without final
int x = 10;
x = 20;          // fine
int y;
y = x / 5;
System.out.println(y);
4
2.15

Displaying numbers & DecimalFormat

learnt›
java
int num = 15;
System.out.print(num);   //print a variable
System.out.print(" ");   //print a string
System.out.print(10);    //print a constant
15 10
  • Use a DecimalFormat object (import java.text.DecimalFormat;) to format numerical output.
  • new DecimalFormat("0.000") → three decimal places (rounded).
  • No-import alternative: String.format("%.3f", num)
DecimalFormat
double num = 123.45789345;
DecimalFormat df = new DecimalFormat("0.000");
System.out.println(num);
System.out.print(df.format(num));
123.45789345 123.458
String.format
double num = 123.45789345;
String formatted = String.format("%.3f", num);
System.out.println(formatted);
123.458

sample program Ch3Circle → Ch3Circle3

Ch3Circle
final double PI = 3.14159;
double radius, area, circumference;
radius = 2.35;
area = PI * radius * radius;
circumference = 2.0 * PI * radius;
System.out.println("Given Radius: " + radius);
System.out.println("Area: " + area);
System.out.println("Circumference: " + circumference);
Given Radius: 2.35 Area: 17.349430775000002 Circumference: 14.765473
Ch3Circle3
import java.text.*;
final double PI = 3.14159;
final String TAB = "\t";
final String NEWLINE = "\n";
DecimalFormat df = new DecimalFormat("0.000");
radius = 2.35;
...
System.out.println(
 "Given Radius:  " + TAB + df.format(radius) + NEWLINE +
 "Area:          " + TAB + df.format(area) + NEWLINE +
 "Circumference: " + TAB + df.format(circumference));
Given Radius: 2.350 Area: 17.349 Circumference: 14.765

shows: radius value set · usage of constants (PI, TAB, NEWLINE) · usage of control characters \t (tab) and \n (new line) · formatted to 3 d.p.

2.16

Numerical input: Scanner methods

learnt›
java
Scanner scanner = new Scanner(System.in);
int age;
System.out.print("Enter your age: ");
age = scanner.nextInt();
MethodExample
nextByte()byte b = scanner.nextByte();
nextDouble()double d = scanner.nextDouble();
nextFloat()float f = scanner.nextFloat();
nextInt()int i = scanner.nextInt();
nextLong()long l = scanner.nextLong();
nextShort()short s = scanner.nextShort();
nextLine()String str = scanner.nextLine();
2.17

The Math class *** in slides

learnt›
  • Math is in java.lang, automatically imported. It contains class methods for common math functions, called as Math.method().
  • ½ sin(x − π/√y) in Java: (1.0 / 2.0) * Math.sin( x - Math.PI / Math.sqrt(y) )
MethodDescription
exp(a)natural number e raised to the power of a
log(a)natural logarithm (base e) of a
floor(a)largest whole number ≤ a
max(a,b)the larger of a and b
pow(a,b)a raised to the power of b
sqrt(a)square root of a
sin(a)sine of a (all trig functions use radians)
2.18

Random number generation *** in slides

learnt›
  • Needed in simulations and games, e.g. rolling a die → integer between 1 and 6.
  • Use the Random class from java.util. (Math.random also works but is harder to use.)
  • Most of the time we want integers → the nextInt method.
java
import java.util.Random;
public class Main {
  public static void main(String[] args) {
    Random ran = new Random();
    int num = ran.nextInt(6);
    System.out.println(num);
  }
}
exam trap

random.nextInt() → any int.

ran.nextInt(6) → 0 to 5 (not 6!).

For a die use ran.nextInt(6) + 1 → 1 to 6. General: nextInt(MAX − MIN + 1) + MIN.

✎

Quick self-test · tap to flip

learnt›
Chapter 2 · Part 1

Programmer-Defined Classes

by the end you should be able to…
3.1

Why define our own classes?

learnt›
  • Standard classes (String, GregorianCalendar, JFrame…) won't meet all our needs; we must define classes customised for our applications.
  • It's the first step toward the skills needed to build large programs.
  • Classes we define ourselves = programmer-defined classes.
BicycleRegistration (uses Bicycle)
class BicycleRegistration {
  public static void main(String[] args) {
    Bicycle bike1, bike2;
    String  owner1, owner2;
    bike1 = new Bicycle( );
    bike1.setOwnerName("Adam Smith");
    bike2 = new Bicycle( );
    bike2.setOwnerName("Ben Jones");
    owner1 = bike1.getOwnerName( );
    owner2 = bike2.getOwnerName( );
    System.out.println(owner1 + " owns a bicycle.");
    System.out.println(owner2 + " also owns a bicycle.");
  }
}
Bicycle (the definition)
class Bicycle {
  // Data Member
  private String ownerName;
  //Constructor: Initialises the data member
  public void Bicycle( ) {
    ownerName = "Unknown";
  }
  //Returns the name of this bicycle's owner
  public String getOwnerName( ) {
    return ownerName;
  }
  //Assigns the name of this bicycle's owner
  public void setOwnerName(String name) {
    ownerName = name;
  }
}
Adam Smith owns a bicycle. Ben Jones also owns a bicycle.
exam trap, spotted on the slideThe slide labels public void Bicycle( ) as the constructor, but a real constructor has NO return type. With void it becomes an ordinary method that never runs automatically (see Kitty example 2 in 3.6). The correct form is public Bicycle( ) { … }.
3.2

Multiple instances

learnt›

Once the Bicycle class is defined, we can create multiple instances; each has its own copy of ownerName.

bike1
→
: Bicycle
ownerName"Adam Smith"
bike2
→
: Bicycle
ownerName"Ben Jones"
ONE object
A a = new A();
for (int i = 0; i < 10; i++) {
  String keyedinname = scanner.nextLine();
  a.setname(keyedinname);
}

1 object created → its name is overwritten 10 times on the SAME object

TEN objects
for (int i = 0; i < 10; i++) {
  A a = new A();
  String keyedinname = scanner.nextLine();
  a.setname(keyedinname);
}

a NEW object every iteration → 10 objects in total

3.3

Class diagram & class template

learnt›

class diagram for Bicycle

Bicycle
Bicycle( ) ← constructor getOwnerName( ) setOwnerName(String)

method listing: list the name and the data type of any argument passed to the method

template for a class definition

Import statements
→
Class comment
→
class Class Name {
→
Data members
→
Methods (incl. constructor) }
3.4

Declaring data members & methods

learnt›

data member declaration

privatemodifiers
Stringdata type
ownerNamename
; 

<modifiers> <data type> <name>; · only one modifier in this example

method declaration

publicmodifier
voidreturn type
setOwnerNamemethod name
( String name )parameter
{ ownerName = name; }statements

<modifier> <return type> <method name> ( <parameters> ) { <statements> }

  • void → a method that does not return a value (e.g. setOwnerName).
  • Value-returning method → when called, returns a value to the caller. getOwnerName() returns the value of instance variable ownerName, which was declared as String, so its return type is String.
  • A value-returning method must have return <expression>;
  • The expression's type must be compatible with the declared return type: if the return type is int, you can return int, short or byte.
3.5

Constructors

learnt›
  • A constructor is a special method executed when a new instance of the class is created.
  • Syntax: public <class name> ( <parameters> ) { <statements> }. <class name> = the class this constructor belongs to.
  • Same name as the class · NO return type (not even void)
  • Purpose: initialise data members. For Bicycle, set the owner name to a value that shows no real name is assigned yet.
  • Since it runs when the instance is created, it's the most logical place to initialise data members and do other set-up tasks.

constructor anatomy

publicmodifier
Bicycleclass name
( )parameter
{ ownerName = "Unassigned"; }statements
3.6

Constructor code examples (Kitty)

learnt›

example 1: who makes the constructor?

no constructor written
public class Kitty{
  public static void main(String []args){
    Kitty myKitty = new Kitty( );}
}
written by programmer
public class Kitty{
  public Kitty(){
    //no need this constructor
  }
  public static void main(String []args){
    Kitty myKitty = new Kitty( ); }
}
lecturer's question: "auto constructor created by compiler?"Yes. If you write no constructor, the compiler adds a default no-argument constructor automatically. Both programs run fine ("Program finished"), so the empty one on the right isn't needed.

example 2: constructor vs method with the same name

Kitty as constructor
public class Kitty{
  public Kitty(String name){
    System.out.println("Passed Name is :" + name);
  }
  public static void main(String []args){
    Kitty myKitty = new Kitty("molly");
  }
}
Passed Name is :molly
Kitty as method
public class Kitty{
  String name;
  public void Kitty(){
    System.out.println("Passed Name is :" + name);
  }
  public static void main(String []args){
    Kitty myKitty = new Kitty( );
    myKitty.name = "molly";
    myKitty.Kitty();
  }
}
exam trapAdd void and Kitty() stops being a constructor. It's a normal method that you must call yourself (myKitty.Kitty()).
3.7

Using several classes together

learnt›
SecondMain: one more class added
class SecondMain {
  public static void main(String[] args) {
    Bicycle bike;
    Account acct;
    String  myName = "Jon Java";
    bike = new Bicycle( );
    bike.setOwnerName(myName);
    acct = new Account( );
    acct.setOwnerName(myName);
    acct.setInitialBalance(250.00);
    acct.add(25.00);
    acct.deduct(50);
    System.out.println(bike.getOwnerName() + " owns a bicycle and");
    System.out.println("has $ " + acct.getCurrentBalance() +
                       " left in the bank");
  }
}
Account
class Account {
  private String ownerName;
  private double balance;
  public Account( ) {
    ownerName = "Unassigned";
    balance = 0.0;
  }
  public void add(double amt) {
    balance = balance + amt; }
  public void deduct(double amt) {
    balance = balance - amt; }
  public double getCurrentBalance( ) {
    return balance; }
  public String getOwnerName( ) {
    return ownerName; }
  public void setInitialBalance(double bal) {
    balance = bal; }
  public void setOwnerName(String name) {
    ownerName = name; }
}
Jon Java owns a bicycle and has $ 225.0 left in the bank

250.00 + 25.00 − 50 = 225.0

Main.java: multiple classes in one file
class Demo {
  public void compute(int i, int j, double x) {
    double result = i + j + x;
    System.out.println("Computation result: " + result);
  }
}
class Account {
  private double balance = 0.0;
  public void add(double amt) {
    balance = balance + amt;
    System.out.println("Current Balance: " + balance);
  }
}
public class Main {
  public static void main(String[] args) {
    Account acct = new Account();
    acct.add(400);
    Demo demo = new Demo();
    int i = 5;
    int k = 14;
    demo.compute(i, k, 20);
  }
}
Current Balance: 400.0 Computation result: 39.0
noticeOnly the class holding main is public, and the file is named after it (Main.java). Passing int 400 to a double parameter prints 400.0, and 5 + 14 + 20.0 = 39.0.
3.8

Arguments & parameters

learnt›
  • Argument = a value we pass to a method (caller side), e.g. acct.add(400); → 400 is the argument.
  • Parameter = a placeholder in the called method that holds the passed value, e.g. add(double amt) → amt is the parameter.

matching them up

passing side
i (5)
k (14)
20
→→→ receiving side
int i
int j
double x

demo.compute(i, k, 20) → compute(int i, int j, double x) · 3 arguments ↔ 3 parameters

3 matching rules

① The number of arguments and parameters must be the same.

② They are paired left to right.

③ Each pair must be assignment-compatible. You can't pass a double argument to an int parameter.

3.9

Information hiding & visibility modifiers

learnt›
  • public and private set the accessibility of data members and methods.
  • private → client classes cannot access it. public → client classes can.
  • Declaring a class's internal details private and hiding them from clients = information hiding.

accessibility example: client → service

Client
Service obj = new Service();
obj.memberOne = 10;   // ✓ public
obj.memberTwo = 20;   // ✗ private
obj.doOne();          // ✓ public
obj.doTwo();          // ✗ private
Service
class Service {
  public  int memberOne;
  private int memberTwo;
  public void doOne() { … }
  private void doTwo() { … }
}
ruleData members should be private: they're implementation details, invisible to clients.

Exception: constants can (should) be public if outside methods are meant to use them directly.

UML visibility: + public − private

AccountVer2
− balance− ownerName
+ AccountVer2( String, double )+ add( double )+ deduct( double )+ getCurrentBalance( )+ getOwnerName( )+ setOwnerName( String )
3.10

Access modifiers * in slides

learnt›
  • Access modifiers help implement the encapsulation principle of OOP.
  • Java has 4 access modifiers: public, protected, default (package-private), private.
  • Other (non-access) modifiers: static, final, abstract.

from most open to most closed

publiceveryone
→
protectedpackage + subclasses
→
defaultno keyword · same package
→
privateown class only
lecturer's question: "default (package-private?)"Yes. If you write no modifier, the member is visible only to classes in the same package. That's why the Carpeting example below works in both layouts.
main within the class
import java.util.Scanner;
class Carpeting {
  //Attribute (default access)
  int length;
  int width;
  float price;
  //Method
  public void calculatePrice() {
    System.out.println("The carpet price is :RM"
      + length * width * price);
  }
  // Main Method
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Carpeting carpet = new Carpeting();
    System.out.println("Enter the room length (ft.):");
    carpet.length = in.nextInt();
    System.out.println("Enter the room width (ft.) :");
    carpet.width = in.nextInt();
    System.out.println("Enter the carpet price per sq. ft. :");
    carpet.price = in.nextFloat();
    carpet.calculatePrice();
  }
}
main separated · A.java
import java.util.Scanner;
class Carpeting {
  int length;
  int width;
  float price;
  public void calculatePrice() {
    System.out.println("The carpet price is :RM"
      + length * width * price);
  }
}
public class A {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Carpeting carpet = new Carpeting();
    ...same input lines...
    carpet.calculatePrice();
  }
}
3.11

Constants in a class (Die)

learnt›
java
import java.util.Random;
class Die {
  private static final int MAX_NUMBER = 6;
  private static final int MIN_NUMBER = 1;
  private static final int NO_NUMBER  = 0;
  private int number;
  private Random random;
  public Dice( ) {              // should be Die( )
    random = new Random();
    number = NO_NUMBER;
  }
  //Rolls the dice
  public void roll( ) {
    number = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
  }
  //Returns the number on this dice
  public int getNumber( ) {
    return number;
  }
}
  • static final → one shared copy (class constant) whose value can't change.
  • nextInt(6 − 1 + 1) + 1 = nextInt(6) + 1 → 1 to 6.
exam trapThe class is Die but the constructor is written Dice( ). A constructor's name must match the class name, so this won't compile (Java sees a method with no return type).
lecturer's question: "main should be added?"Only if you want to run Die on its own. Normally another class (with main) creates a Die and calls roll() / getNumber().
3.12

Local vs instance variables vs parameters

learnt›
java
class MusicCD {
  private String artist;
  private String title;
  private String id;
  public MusicCD(String name1, String name2) {
    String ident;
    artist = name1;
    title  = name2;
    ident  = artist.substring(0,2) + "-" +
             title.substring(0,9);
    id     = ident;
  }
  ...
}

where each variable lives

instance variablesartist · title · id
declared in the class · live as long as the object
parametersname1 · name2
receive the arguments
local variableident
declared inside the constructor · gone when it ends

flow: name1 → artist, name2 → title, then artist + title build ident, then ident → id (saved in the object)

3.13

Abstract, same-class calls, main class *** in slides

learnt›
abstract example
// You cannot do: Shape s = new Shape(); // ERROR!
abstract class Shape {
  String color;
  public void setColor(String color) {
    this.color = color;
  }
  public static void main(String[] args) {
    System.out.println("Look at the abstract conceptual");
  }
}
rememberAn abstract class is a concept only. You cannot create an object of it with new.
  • So far we called methods of another class (object). You can also call a method from another method of the same class.
  • In that case, just use the method name, no dot notation.

calling methods

:AClass
BClass obj = new BClass();obj.doWork();

dot notation is necessary when calling a method of another object

:BClass
public void doWork(){…}public void myMethod(){  doWork(); }

dot notation is optional when calling a method of the same object

  • Any class can be a main class: just include the main method.
java
class Bicycle {
  //definition of the class as shown before comes here
  public static void main(String[] args) {
    Bicycle myBike;
    myBike = new Bicycle( );
    myBike.setOwnerName("Jon Java");
    System.out.println(myBike.getOwnerName() + "owns a bicycle");
  }
}
✎

Quick self-test · tap to flip

learnt›
Chapter 2 · Part 2

The this Keyword & Overloading

by the end you should be able to…
4.1

Keyword this

learnt›
  • Use this in any method or constructor to refer to the current object, the one that called the method or invoked the constructor.
  • There are many uses; we focus on the first two:
    • this.variable → refers to the current class instance variable
    • this() → invokes the current class constructor
this.radius = radius
public class Circle {
  double radius;  // member variable
  public Circle(double radius) { // argument
    this.radius = radius;
    System.out.println(radius);
  }
  public static void main(String [] args){
    Circle circle = new Circle(789);
  }
}
789.0
the difference
public Circle(double radius) {
  this.radius = 500;
  System.out.println(radius);
  System.out.println(this.radius);
}
...
Circle circle = new Circle(789);
789.0 500.0

which "radius" is which?

radiusresolves to the method's argument (789.0)
this.radiusrefers to this instance's member variable (500.0)
→
circle : Circle
radius500.0
  • To avoid the naming conflict, you could rename the field (e.g. Rad_radius = radius;), but radius is more meaningful, so Java gives us this to resolve the conflict.
problem: no this
class Student10{
  int id;
  String name;
  Student10(int id, String name){
    id = id;       //supposed to be this.id
    name = name;   //supposed to be this.name
  }
  void display(){System.out.println(id+" "+name);}
  public static void main(String args[]){
    Student10 s1 = new Student10(111,"Karan");
    Student10 s2 = new Student10(321,"Aryan");
    s1.display();
    s2.display();
  }
}
0 null 0 null
correction: with this
Student10(int id, String name){
  this.id = id;
  this.name = name;
}
111 Karan 321 Aryan
exam trapWithout this, id = id assigns the parameter to itself. The fields keep their defaults: 0 for int and null for String.
this NOT required
class Student12{
  int id;
  String name;
  Student12(int i, String n){
    id = i;
    name = n;
  }
  void display(){System.out.println(id+" "+name);}
  ...
  Student12 e1 = new Student12(111,"karan");
  Student12 e2 = new Student12(222,"Aryan");
}
no confusion hereParameter names (i, n) are different from the field names (id, name), so this isn't needed.
4.2

Method overloading

learnt›
  • Method overloading = the same method name with different implementations (versions).
  • The versions must be distinguishable by their argument list: number, type, or order of arguments.
  • The caller picks a version by supplying the matching arguments.
TestMethodOverloading
public class TestMethodOverloading {
  public int average(int n1, int n2) {              // A
    return (n1 + n2) / 2;
  }
  public double average(double n1, double n2) {     // B
    return (n1 + n2) / 2;
  }
  public int average(int n1, int n2, int n3) {      // C
    return (n1 + n2 + n3) / 3;
  }
  public static void main(String[] args) {
    TestMethodOverloading tester = new TestMethodOverloading();
    System.out.println(tester.average(1, 2));       // Use A
    System.out.println(tester.average(1.0, 2.0));   // Use B
    System.out.println(tester.average(1, 2, 3));    // Use C
    System.out.println(tester.average(1.0, 2));     // Use B
    // System.out.println(tester.average(1, 2, 3, 4)); // Compilation Error
  }
}

which version gets called?

CallVersionResultWhy
average(1, 2)A (int, int)13 / 2 → integer division
average(1.0, 2.0)B (double, double)1.5exact type match
average(1, 2, 3)C (int, int, int)23 arguments
average(1.0, 2)B1.5int 2 implicitly cast to 2.0
average(1, 2, 3, 4)nonecompile errorno matching method
4.3

Constructor overloading & packages

learnt›
  • Like methods, constructors can also be overloaded: several constructors, each with a different parameter list.
  • package Overload; as the first line puts the class into the package Overload. That's how classes are organised into a package.
StudentData
package Overload;
public class StudentData {
  private int stuID;
  private String stuName;
  private int stuAge;
  StudentData() {                       // default constructor
    stuID = 100;
    stuName = "New Student";
    stuAge = 18;
  }
  StudentData(int num1, String str, int num2) { // parameterized
    stuID = num1;
    stuName = str;
    stuAge = num2;
  }
  //Getter and setter methods
  public int getStuID() { return stuID; }
  public void setStuID(int stuID) { this.stuID = stuID; }
  public String getStuName() { return stuName; }
  public void setStuName(String stuName) { this.stuName = stuName; }
  public int getStuAge() { return stuAge; }
  public void setStuAge(int stuAge) { this.stuAge = stuAge; }
}
class TestOverloading {
  public static void main(String args[]) {
    StudentData myobj = new StudentData();            // default
    ...print name, age, ID...
    StudentData myobj2 = new StudentData(555, "Chaitanya", 25); // parameterized
    ...print name, age, ID...
  }
}

two objects, two constructors

myobj
→
: StudentData
stuNameNew StudentstuAge18stuID100

via StudentData()

myobj2
→
: StudentData
stuNameChaitanyastuAge25stuID555

via StudentData(int, String, int)

Student Name is: New Student Student Age is: 18 Student ID is: 100 Student Name is: Chaitanya Student Age is: 25 Student ID is: 555
another example: Circle
public Circle() {                   // 1st Constructor
  radius = 1.0;
  color = "red";
}
public Circle(double r) {           // 2nd Constructor
  radius = r;
  color = "red";
}
public Circle(double r, String c) { // 3rd Constructor
  radius = r;
  color = c;
}
noticeThe setters use this.stuID = stuID because the parameter has the same name as the field, which is exactly the case from 4.1.
✎

Quick self-test · tap to flip

learnt›

you've got this · good luck on the quiz