Lecture 2 Objects and Classes

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Classes Overview l Classes as Types l Declaring Instance Variables l Implementing Methods l Constructors l Accessor and Mutator Methods.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Object Oriented Programming Classes and Objects Dr. Mike Spann
Writing Classes (Chapter 4)
Object Oriented Programming Concepts OOP – reasoning about a program as a set of objects rather than as a set of actions Object – a programming entity.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Constructors and Encapsulation reading: self-checks: #10-17.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, this reading: self-checks: #13-17 exercises:
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
EE2E1. JAVA Programming Lecture 3 Java Programs and Packages.
Object Oriented Programming Classes and Objects Dr. Mike Spann
10-Nov-15 Java Object Oriented Programming What is it?
EE2E1. JAVA Programming Lecture 3 Inheritance. Contents Base classes and derived classes Base classes and derived classes Protected scope Protected scope.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Topics Instance variables, set and get methods Encapsulation
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Constructors; Encapsulation reading: self-checks: #13-18,
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Topic: Classes and Objects
Lecture 3: Introduction to Object and Classes
Static data members Constructors and Destructors
Examples of Classes & Objects
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Final and Abstract Classes
Chapter 3: Using Methods, Classes, and Objects
Templates.
CS 302 Week 10 Jim Williams.
Object Based Programming
Chapter 9 Inheritance and Polymorphism
Class Structure 16-Nov-18.
Corresponds with Chapter 7
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Chapter 4: Writing classes
Classes & Objects: Examples
Building Java Programs
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Group Status Project Status.
Class Structure 7-Dec-18.
Object Oriented Programming in java
Building Java Programs
Classes and Objects.
Class Structure 2-Jan-19.
Announcements Program 2 is due tomorrow by noon Lab 4 was due today
Class Structure 25-Feb-19.
Chapter 9 Objects and Classes
Dr. R Z Khan Handout-3 Classes
OO Programming Concepts
Final and Abstract Classes
Building Java Programs
Chapter 11 Inheritance and Encapsulation and Polymorphism
Chapter 7 Objects and Classes
CSG2H3 Object Oriented Programming
Chapter 5 Classes.
Presentation transcript:

Lecture 2 Objects and Classes EE2E1. JAVA Programming Lecture 2 Objects and Classes

Contents Using existing classes Creating new classes private/public access Implementation/interface Constructors this object reference Objects as function arguments static methods

Using existing classes We have already seen examples of classes in Java System Math Arrays String There are 100’s more which come with all the various Java API’s These classes are grouped into packages The documentation for all Java classes is at http://java.sun.com/j2se/1.5.0/docs/api/index.html

Example Java provides a Date class for representing the time and date Date date = new Date(); // Initialized to current // time and date Effectively, object date is a pointer to a Date variable Date Friday Oct 16, 2004 12:07pm date

Class methods (member functions) These specify the functionality of the class They are called through the object name Date date = new Date(); int h=date.getHours(); int m=date.getMonth();

We can think of these methods as operating on the objects – they are called through the object variable name Date date Friday Oct 16, 2004 12:07pm Date date = new Date(); int h=date.getHours(); // returns 12 int m=date.getMonth(); // returns 10 The object has to exist before one of its methods can be called

Creating new classes A class consists of class methods and instance fields Methods specify the functionality of the class (what we can do with objects of the class) Instance fields specify the state of the objects

Example A StudentInfo class is used to store student records information 2 (public) methods StudentInfo(..) – a method with the same name as the class, known as a constructor printInfo() 3 (private) instance fields name idNumber address

public class StudentInfo { public StudentInfo(String n, int id, String a) name=new String(n); idNumber=id; address=new String(a); } public void printInfo() System.out.println(name + “ ”+ idNumber + “ ” + address); private String name; private int idNumber; private String address;

public class StudentInfoTest { public static void main(String[] args) StudentInfo si1=new StudentInfo(“John Smith”, 3429, “21 Bristol Rd”); StudentInfo si2=new StudentInfo(“Alan Jones”, 5395, “30 Bournbrook Rd”); si1. printInfo(); si2.printInfo(); }

StudentInfoTest class creates StudentInfo objects using the new operator The constructor is automatically called from the new StudentInfo(…) statement Calling the constructor initializes the objects Method printInfo() called from the 2 object variables si1 and si2 Class StudentInfoTest is made public which gives it public scope. The class is visible outside of its package.

private/public access Keyword private means only methods in the StudentInfo class can access these fields Keyword public means the method can be called from any other method in any other class

Accessed from anywhere StudentInfo public StudentInfo() printInfo() private Accessed only by String name int idNumber String address

Generally, instance fields are private They represent the implementation of the class Methods are generally public They represent the interface to the class The separation of a class into public/private is a key feature of object-oriented programming Sometimes known as encapsulation in OO circles

Implementation/interface (state/behaviour) The implementation of a class is specified in the private instance fields They are hidden from outside the class The interface to the class is specified by the public methods They can be accessed from anywhere The implementation may change but the interface must stay the same

Example Class Point represents the position in the 2D (x-y) plane { public Point(int x, int y) { xpos=x; ypos=y;} public int getX() { return xpos;} public int getY() { return ypos; } private int xpos, ypos; }

Suppose this class is used to represent a polygon as an array of points – also includes a method to compute the perimeter The x and y co-odinates are accessed through methods getX() and getY()

class Polygon { public Polygon() {…} public double perimeter() double pm=0; int nn; for (int n=1; n<numVertices; n++) int xv1= vertices[n-1].getX(); int yv1=vertices[n-1].getY(); nn=n%numVertices; int xv=vertices[nn].getX(); int yv=vertices[nn].getY(); pm+=(Math.sqrt((xv1-xv)*(xv1-xxv)+(yv1-yv)*(yv1-yv))); } return pm; private Point[] vertices; private int numVertices;

The key point is that we can change the implementation of Point to use polar co-ordinates The implementation of the Polygon class (and in particular the perimeter() method) doesn’t change We have created a re-useable software component Point

class Point { public Point(int x, int y) r=Math.sqrt(x*x+y*y); theta=Math.atan2(y,x); } public int getX() return r*Math.cos(theta); public int getY() return r*Math.sin(theta); private float r, float theta;

Constructors Constructors are special methods for initialising an object It must have the same name as the class and not have a return type Constructors can be overloaded A class can have several constructors with different arguments

Example An Employee class can be used to store information about employees in a company Constructor Employee() is the default constructor Used for creating un-initialized objects Constructor Employee(String, int) initializes the instance fields name and age EmployeeTest class creates Employee objects using both constructors

class Employee { public Employee() // default constructor {} public Employee(String n, int a) name=new String(n); age=a; } private String name; private int age;

public class EmployeeTest { public static void main(String[] args) Employee emp=new Employee(); // default cnstr. Employee emp1=new Employee(“John Smith”,35); }

The this object reference Allows access to the current object as a whole and not just particular instance fields The keyword this refers to the object on which the method operates One simple use of this is to force the default constructor to call another constructor There are many other uses for this

class Employee { public Employee() // default constructor this(“No name”, 0); // Call other constructor } public Employee(String n, int a) name=n; age=a; private String name; private int age;

Objects as function arguments Object names are references (pointers!) to the objects It is tempting to think that object arguments to functions are effectively passed by reference This means that objects can be changed inside functions Unfortunately this is wrong – the object references are passed by value!! The object state can be changed by calling mutator methods of the object inside the function

class Employee { public Employee() {}// default constructor public Employee(String n, int a) name=new String(n); age=a; } public void incrementAge() {age++;} private String name; private int age;

class changeEmployeeDetails { static void swap(Employee e1, Employee e2) Employee temp=e2; e2=e1; e1=temp; } static void incrementAge(Employee e) e.incrementAge();

public class EmployeeTest { public static void main(String[] args) Employee emp=new Employee(“John Smith”,35); Employee emp1=new Employee(“John Smith”,36); // Update age? changeEmployeeDetails.swap(emp,emp1); // emp.age still 35! // Update age changeEmployeeDetails.incrementAge(emp); // emp.age now 36 }

In the first case, the swap() method doesn’t change the state of the object After the method is called, emp still refers to the 35 y/o John Smith The object references are passed by value and hence don’t change on exit from the function

Start of swap() In swap Employee emp John Smith 35 Employee emp1 36 In swap e1 e2

End of swap() In swap Employee emp John Smith 35 Employee emp1 36 In swap e1 e2

In the second case, incrementAge() is a mutator method which changes the age instance field of an Employee object Method incrementAge() in class changeEmployeeDetails() can then update the age of the Employee object passed by reference The object reference has not been changed, just the object’s internal state

Static methods Static methods belong to the class and are called through the class name We have already seen examples of static methods Console.readDouble() Math.pow(x,y) Arrays.sort() We don’t need to create an object (instantiate the class) in order to call a static method The main() method in a class is static which means the Java interpreter can start the main() method without creating an object public static void main(String[] args)

Static methods cannot access the instance fields (which belong to objects) classes can also have static fields, which again belong to the class and not the objects These are typically constants defined in the context of the class Example – the Color class has 13 public static fields representing colour constants – Color.black, Color.red etc

class MyClass private int n; private static int m=15; public MyClass(int nn) {n=nn;} MyClass obj1=new Myclass(10); MyClass obj2=new Myclass(20); obj1 obj2 n=10 n=20

Example Static methods cannot access non-static instance fields – vice versa is OK A common error is to try and access a non-static from main public class SayHello { public static void main(String[] args) System.out.println(message); // Error! message non-static } private String message=“Hello”;

The static method main cannot access the non-static instance field message Need to declare message as static for this program to work private static String message=“Hello”;

And finally….. There has been a lot of detail in this lecture Its important to appreciate the significance of encapsulation – implementation/interface as well as the difference between static and non-static members In the first assessed programming lab exercise, you will have to design and implement a number of classes to create a relatively sophisticated application