0% found this document useful (0 votes)
7 views

08IntroClasses

The document outlines an introduction to classes and objects in Java, covering topics such as built-in classes, creating custom classes, and the concept of instance variables and methods. It explains the structure of class definitions, the role of constructors, and the use of visibility modifiers. Additionally, it provides examples of object instantiation and method usage, emphasizing the importance of encapsulation and proper naming conventions.

Uploaded by

Nhân Trọng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

08IntroClasses

The document outlines an introduction to classes and objects in Java, covering topics such as built-in classes, creating custom classes, and the concept of instance variables and methods. It explains the structure of class definitions, the role of constructors, and the use of visibility modifiers. Additionally, it provides examples of object instantiation and method usage, emphasizing the importance of encapsulation and proper naming conventions.

Uploaded by

Nhân Trọng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

CompSci 230 S2 2017

Programming Techniques
Introduction to Classes and Objects
Agenda & Reading
 Topics:
 Introduction
 Built-In Classes in Java
 Creating Classes
 Class Variables & Methods
 Reading
 Java how to program Late objects version (D & D)
 Chapter 7
 The Java Tutorial
 Classes:
 http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html
 Objects
 http://docs.oracle.com/javase/tutorial/java/javaOO/objects.html
2 02
1.Introduction
 Class
 A set of objects with shared behaviour and individual state
 Individual state:
 Data is stored with each instance, as an instance variable.
 Shared behaviour:
 Code is stored with the class object, as a method.
 Shared state may be stored with the class object, as a class variable.
 Object
 Objects are created from classes at runtime by instantiation
 usually with the “new” operator.
 There may be zero, one, or many objects (instances) of a class.
 Instantiated objects are garbage-collected if no other
user-defined object can reference them.
Each instance, or object, has its
own property values that may differ
from those of other objects of the
same kind

3 02
1.Introduction
What is an Object?
 A building block for OO development
 Like objects in the world around us
 Objects have state and behaviour
 Examples:
 Dog
 State/field/attribute: name, colour, isHungry, …
 Behaviour: bark(), fetch(), eat(), …
 Car
 State: make, model, speed, number of doors, …
 Behaviour/operation: accelerate, decelerate, open bonnet …
 VCR
 State: brand, colour, isOn …
 Behaviour: play(), stop(), rewind(), turnOn(), …
4 02
2. Built-In Classes in Java
 Java provide some useful classes in the java.awt package.
 These classes provide us with some methods and fields that help us
save time and effort in writing code and repeating it more and
more…
 Example:
 Point class : A point representing a location in (x,y) coordinate space,
specified in integer precision.
 Fields: x-coordinate, y-coordinate
 Rectangle class: A rectangle specifies an area in a coordinate space that is
defined by the rectangle's top-left point (x, y) in the coordinate space, its
width, and its height. Point Rectangle
 Fields: top-left point (x,y), width and height x =23 x =0
 Creating Objects from Java built-in classes y = 94 y=0
width=50
 Declaration
height=100
 Instantiation
 Initialization
5 02
2. Built-In Classes in Java
Creating Objects No object has been
 Declaration: Point p; created with this
declaration.
 Declaring a Variable to Refer to an Object
 Note: a variable either holds a primitive type, or it holds a
reference to an object. p
2
Point p2 = new Point(23, 94); x 23
 Instantiation & Initialization: y 94
 The new keyword is a Java operator that creates the object.
This is known as instantiating a class.
 The new operator allocates memory for the new object
 The new operator returns a reference to the object it created
 The new operator is followed by a call to a constructor.
 For example, Point(23, 94) is a call to Point's only constructor.
The constructor initializes the new object with x is 23 and y
is 94
6 02
L08Code.ja
2. Built-In Classes in Java va

Examples:
 Objects: originOne, rectOne, rectTwo originOne:
Point
Remember to add x =23
import java.awt.Point; the import y = 94
import java.awt.Rectangle; statements
rectOne:
public class L08Code { Rectangle
public static void main(String[] args){
x =10
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(10, 20, 100, 200); y = 20
Rectangle rectTwo = new Rectangle(50, 100); width=100
System.out.println(rectOne.getWidth());
height=200
System.out.println(rectTwo.getLocation());
System.out.println(originOne.toString());
} rectTwo:
} Rectangle
x =0
100.0 y=0
java.awt.Point[x=0,y=0]
width=50
java.awt.Point[x=23,y=94]
height=100
7 02
3.Creating Classes
 We can write our own classes that define specific objects that we
need.
 Each class you create becomes a new type that can be used to declare
variables and create objects.
 A class definition has two parts: a class declaration and a class body.
 Class declaration
 contains keyword “class” followed immediately by the class’s name.
 Class body class MyClass {
 contains //field and method declarations
}
 constructors for initializing new objects,
 declarations for the variables that provide the state, and
 methods to implement the behavior of the class and its objects.
 Note: Each class declaration that begins with the access modifier public
must be stored in a file that has the same name and ends with the .java
extension.
 Class, method and variable names are identifiers. (i.e. all use camel case
names.)
8 02
3.Creating Classes
Instance Variables
 Instance variables are dynamically allocated,
 So they may have different values in each instance
of an object.
 A class declares the type of the data, but it does not
reserve any memory space for it
 When an object is instantiated, the runtime system b1: Ball
allocates some memory to this instance – so that it xPos=10
can “remember” the values it stores in instance b2: Ball
yPos = 20
variables carried with it throughout its lifetime. xPos =10
Color = Red
 Instance variables exist before methods are called yPos = 10
on an object. Color =
Blue
 A class normally contains one or more methods that b3: Ball
manipulate the instance variables that belong to
xPos = 5
particular objects of the class.
yPos = 5
 Instance variables are declared inside a class Color =
declaration but outside the bodies of the class’s Green
9 method declarations. 02
3.Creating Classes
Visibility Modifiers
 Java provides a number of access modifiers to set
access levels for classes, variables, methods and
constructors. There are four levels but we look at two
levels first.
 Members of a class that are declared with public visibility can
be accessed from anywhere
 Members of a class that are declared with private visibility can
only be access from inside the class
 As a general rule
 No object's data should be declared as public.
 Methods are usually declared as public so that they can be
invoked by the clients
 A method created simply to assist a service method is called a
support method and should not be declared as public
10 02
Car.jav public class Car {
3.Creating Classes a private String make;
private String model;
Instances of Car private int year;
private int speed;
Car c1 = new Car("Nissan", "Leaf", 2010, 4); private int doors;
Car c2 = new Car("Bentley", "Hunaudieres", 1999, 2); private boolean openBonnet;
Car c3 = new Car("Ford", "Mustang", 2008, 2);
...
 Pictures: }

 Objects in memory:

11 02
3.Creating Classes
Constructors
 Constructors are invoked to create objects from the class
blueprint and initialize instance variables.
 It looks like method declarations — except that they use the
name of the class, can specify parameters but no return
type.
 It automatically called when an object is created using
the new operator
 Note: Java requires a constructor call for every object that’s
created.
 It could have more than one constructors (i.e. overloading)
 Each constructor has a different signature (a public
different number
Point() { of
sequence of argument types) x=0;
public Point() { ... y=0;
public Point(Point p) { ... }
public Point(int x, int y) { ...
12 02
3.Creating Classes
Constructors (con’t)
 Default Constructor
 If a class definition doesn’t include a constructor method,
the Java compiler inserts a default constructor with no
parameters, and the class’s instance variables are
initialized to their default values.
 int:0, String: null, boolean: false
 Recall that local variables are not initialized by default.
 Note: There’s No Default Constructor in a Class That
Declares a Constructor
 If you declare a constructor for a class, the compiler will NOT
create a default constructor forclass
public thatMyMessage
class. { m:
int x; MyMessage
String y; x=0
} must be
careful when y = null
doing this
13 02
3.Creating Classes
Instance Methods
 Instance methods operate on this object's instance variables.

 The operations that can be performed on each object may modify


the property values.
 We typically perform an operation on one object at a time.
 Similar to a class, a method definition has two parts: a
method declaration and a method body.
 A method declaration names the method's access level, return
type, name, arguments.
 The arguments specifies the type and name of each parameter
 The return type indicates the type of value that the methods sends back to
the calling location
Argument
 A method that does not return a value has a void
Return Typereturn type
s
Access public void move(int deltaX, int deltaY) {
Level ...
14 } 02
3.Creating Classes
Example 1: Ball
public class Ball {
public final static int SIZE = 20; Ball.jav
private int xPos; a
private int yPos;
private Color color;  Attributes/Fields
 Represent the internal state of an
public Ball(int x, int y, Color c) {
instance of this class.
xPos = x;
yPos = y;
 Constructor
color = c;  Creates the object
}  Methods
public void move(int deltaX, int deltaY) {
xPos += deltaX;
 Implement the processing performed
yPos += deltaY; by or to an object, often updating its
} state.
...  If there are read and write methods
} for an attribute x, these should be
} called getX() and setX().
 You should learn Java’s conventions for
capitalisation and naming.

15 02
3.Creating Classes
Object Instantiation
 When a constructor method is called, a new instance
isBall
created.
b = new Ball( 10, 20, Color.Red ); b: Ball
Ball c = new Ball( 0, 10, Color.Blue ); 60
xPos = 10
c: Ball yPos = 20 120
xPos = 0 Color = Red
yPos = 10
Color =
Blue
 Message Passing
 In a method call, a message is passed to a receiver object.
 The receiver’s
b.move(50, 100); response to the message is determined by
public class Ball {
its class. ...
public void move(int deltaX, int deltaY) {
message xPos += deltaX;
receiver yPos += deltaY;
arguments }
}

16 02
3.Creating Classes
Instance Method: setXXX & getXXX
 Method getX() returns a particular Ball object’s x-position to the
caller.
 This method has an empty parameter list, so it does not require
additional information to perform its task and just return the value
 Get methods are also commonly called accessor methods
 Method setX() assigns the value of the parameter (an int) to the
class’s xPos instance variable, thus storing the x-position in the
object.
 Note: If a method contains a local variable with the same name as an
instance variable, that method’s body will refer to the local variable rather
than the instance variable.
 The local variable is said to shadow the instance variable in the method’s body.
 You use the keyword this to refer to the shadowed instance variable explicitly
 Set methods
public are also
int getX() { commonly called mutator methods
return xPos; public void setX(int xPos) {
} this.xPos = xPos;
}
17 02
Point b = new Point( 10, 20); b: Point
3.Creating Classes x=

Using the this Keyword y=

 Within an instance method or a constructor, “this” is


a reference to the current object — the object whose
method or constructor is being called.
 Using “this” with a Field
 When an instance variable and local variable share the same
name, you must differentiate between the two by prefixing the
instance variable access with
public Point(int a, intthe
b) use
{ of this.
public Point(int x, int y) {
Either this.x = this.x = a; this.x = x;
a; y = b; this.y = y;
Or } }
x = a; Must use this.x to
refer to the instance
 Using “this” with a Constructor field
 One constructor can call another by using "this"
public Point() {
this(0,0);
}

18 02
Exercise 1
 What is the output?
public class Puppy{
int puppyAge;
public Puppy(String name){
System.out.println("Name chosen is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
Puppy myPuppy = new Puppy( "tommy" );
myPuppy.setAge( 2 );
myPuppy.getAge( );
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
19 02
Stuff.jav
4.Class Variables & Class Methods a

Class Variables
 You specify a class member variable or a class
method by using the static keyword in the member's
declaration.
 A static variable represents classwide information—all
objects of the class share the same piece of data.
 Class variables are statically allocated, so they
 are shared by an entire Class of objects
 The runtime system allocates class variables once per
class, regardless of the number of instances created Stuff of that
class. (i.e. only one copy) X: 10

Static
 public storage
class Stuff { is allocated when the class isa1: loaded.
Stuff a2 : Stuff
public static int x = 10; Stuff a1 = new Stuff();
 } All instances share the same
Stuff a2copy
= new of the class variables
Stuff();
System.out.println(Stuff.x);
20 02
4.Class Variables & Class Methods
Class Methods
 Some methods do work but don’t need an object.
Use the class name instead of an object name to
invoke Math.round(2.3);
Integer.parseInt("123");

 They are called class methods.


 Declare class methods with the static modifier
 Class methods cannot access instance variables.
 Class methods are handled by the “class object” – they can
be called
public even{ if there are no instances of this class.
class Stuff
private static int x = 10;
public static int getX() { ...
}
} System.out.println(Stuff.getX());

21 02
4.Class Variables & Class Methods
Additional Notes
 A static method can call other static methods of the same
class directly (i.e., using the method name by itself) and
can manipulate static variables in the same class directly.
 Java does not allow a static method to directly access instance
variables and instance methods of the same class
 It is because a static method can be called even when no objects of the
class have been instantiated. (i.e. this reference cannot be used in a
static method)
 Instance methods can access all fields (static variables
and instance variables) and methods of the class.
 Many objects of a class, each with its own copies of the instance
variables, may exist at the same time.
 Declaring instance variables private is known as data
hiding or information hiding.
22 02
SharedCounter.ja
va

Examples: Class & Instance variables


Class
public class SharedCounter { variable
private static int count; : Class
sharedCounter:
name = Class
private int value; Instanc
public SharedCounter(int value) { e
this.value = value; variable “SharedCounter”
count = 0 1 2
count++; count = 0 1 2 3
}
public String toString() {
return "value=" + value + " count=" + count;
c1: SharedCounter
}
} value = 10
c2: SharedCounter
value = 100
SharedCounter sc1 = new SharedCounter(10);
c3: SharedCounter
SharedCounter sc2 = new SharedCounter(100);
SharedCounter sc3 = new SharedCounter(200); value = 200
System.out.println(sc1 + " " + sc2 + " " + sc3);

23 02
Exercise 2 Employee bob = new Employee("Bob", "Blue");
Employee susan = new Employee("Susan", "Baker");
System.out.println(Employee.getCount());
 Exercise: 2

 Add a static variable to maintain a count of the number of Employee


objects in memory. (public or private?)
 Complete the constructor …
 Add a static getCount() method (why static?)
class Employee {
private String firstName;
private String lastName;
// complete this

public Employee( String first, String last ) {

public String toString() {


return String.format("%s, %s%n", lastName, firstName);
}
}
24 Lecture09
Exercise 3: MyPoint class
 Complete the constructors
class MyPoint {
private int x;
private int y;
MyPoint p = new MyPoint(10, 20);
public MyPoint() { System.out.println(p);
//complete this MyPoint p2 = new MyPoint();
System.out.println(p2);
}
public MyPoint(int x, int y) {
//complete this (10, 20)
(0, 0)
}

public String toString() {


return String.format("(%d, %d)", x, y);

}
}

25 02
Exercise 4
 Consider the MyPoint class again, what will happen if
the two constructors are declared as private?
class MyPoint {
private int x;
private int y;

private MyPoint() {
...
}
private MyPoint(int x, int y) {
...
}

public class MyPointApp {


public static void main(String[] args) {
MyPoint p = new MyPoint(10, 20);
System.out.println(p);
}
}
26 02

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy