Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:

Slides:



Advertisements
Similar presentations
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
Advertisements

Object Oriented Programming with Java
Chapter 6 Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and.
Based on Java Software Development, 5th Ed. By Lewis &Loftus
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.
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Web Application Development Slides Credit Umair Javed LUMS.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Written by: Dr. JJ Shepherd
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Chapter 6 Introduction to Defining Classes
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Lecture 9 Concepts of Programming Languages
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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 5 Introduction to Defining Classes
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
Topics Instance variables, set and get methods Encapsulation
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Comp1004: Building Better Objects II Encapsulation and Constructors.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 3: Using Methods, Classes, and Objects
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Defining Classes and Methods
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Chapter 7 Objects and Classes
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Basic -2 Classes and Objects

Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects: several Person instances are all around you

Trivial Example: Class Person A Person has some properties Attributes or fields In addition it may have some behavior methods A java class defines properties and behavior common to all people (all Person objects) Each person gets their own field copies

Class Person - example class Person { String name; int height; // in inches int weight; // in pounds // we’ll worry about methods later void setWeight(int newWeight) { } void setHeight(int newHeight){ } }

Objects An object is an instance of a class type An object variable is a reference to the object’s data structure Object variable can be seen as a pointer Declaring an object variabile != creating an object Declaration provides a null pointer Must create an object with the new keyword Calls a constructor method of the class (optionally with arguments) Dynamic allocation Person p1; p1 = new Person(); p1.name = “ your name”; Variable declaration Object instantiation

Object Variables Multiple variables can point to same object A variable can point to NO object its value is null NOTE: passing an object as parameter in a method actually passes a copy of the reference Method manipulates the same referenced object Person p1, p2; p1=new Person(); p1.name = “John”; p2 = p1; System.out.println(p1.name); System.out.println(p2.name); { Person p3; p3=new Person(); p3.name = “Dan”; p2=p3; System.out.println(p2.name); }

Illustration p1 p3 name: “John” height: 0 weight: 0 name: “Dan” height: 0 weight: 0 p2 Java graciously initializes primitive fields for you

Object creation caveats What if we don’t use new ? Person p; System.out.println(p.name); H:>javac Person.java Person.java:15: Variable p may not have been initialized. System.out.println(p.name); ^ 1 error

Second Try Person p = new Person(); p = null; System.out.println(p.name); Compilation works fine but … H:>java Person Exception in thread "main" java.lang.NullPointerException: at Person.main(Person.java:16)

Object equality: == RECALL: variables are references Person p1 = new Person(); Person p2 = new Person(); p1.name = “Jane”; p2.name = “Jane”; If(p1 == p2) System.out.println(“Same!"); else System.out.println(“Different!"); : Person “Jane ” : Person “Jane” p1 p2

More on equality: equals() All classes are equipped with a method equals() For comparing objects of same class Can be (re-)defined wrt class logic boolean equals(Person otherPerson) { if name.equals(otherPerson.name) { System.out.println(“Same!"); return true; } System.out.println(“Different!"); return false; }

Object Destruction Programmer cannot explicitly destroy an instantiated object JVM takes care of “garbage collection” Implicitly frees up memory from “useless” objects Object is useless when program keeps no more references to it e.g when program exits the context where object was created (block, method variables) Or when variables point to other objects or are assigned the null value

Let’s play around with Person … p1.weight = 200; // bad but dealable p1.weight = 700; // unfortunate, but possible p1.weight = -20; // unreal Solution: Have class modify attribute. Allows sanity checks. Provide that behavior through a method p1.setWeight(700); // OK. Weight is now 700. p1.setWeight(-20); *** Error, weight must be positive number // weight still 700

Solution? … class Person { … void setWeight(int newWeight) { if (newWeight < 0) System.err.println( “*** Error, weight must be positive number”); else weight = newWeight; }

… New problem p1.setWeight(-20); *** Error, weight must be positive number p1.weight = -20; // Yo, I’m the boss Assigning weight directly bypasses sanity check by the setWeight() method. We still have a problem. Solution: change attribute visibility to make the bare weight attribute inaccessible from outside Person

New solution Class Person { private String name; private int height; // in inches private int weight; // in pounds public void setWeight(int newWeight) { if (newWeight < 0) System.err.println( “*** Error, weight must be positive number”); else weight = newWeight; } Within same class no dot notation and no visibility issues

New solution in action class Test { public static void main(String args[]) { Person p1 = new Person(); p1.weight = 20; } >javac Test.java >Test.java:4: Variable weight in class Person not accessible from class Test. p1.weight = 20; ^ 1 error Denied!

Finish up Need to add a getWeight(), since we can no longer access weight directly public int getWeight(void) { return weight; } Also, need get() and set() functions for name and height.

Accessor Functions for Encapsulation Generally make fields private and provide public getField() and setField() accessor functions. For this course – ALWAYS unless there’s a specific reason not to Usually there isn’t Need to justify explicitly otherwise! Encapsulation keeps programs tidy Enables clear definition of interactions between classes Public parts of a class represents its Application Programming Interfaces (API) Private parts hide details of the class implementation If interface remains stable, even if implementation changes, the rest of application is unaffected Example: height in cm. and weight in Kg.

More on Visibility Methods / Attributes public private package (default) protected /** Represents a 2d geometric point */ package 2d; class Point { private float x,y; // coordinates public Point(float coordX, float coordY){ x=coordX; y=coordY; } public void move(float dX, float dY){ x+=dX; y+=dY; } public String desc(){ return “Point (" + x + ", " + y + ")"; } Constructor with parameters Point - float x,y + Point(float, float) + move(float dx, float dy) + String desc() At-a-glance look at the class API

Constructors Multiple constructors with different sets of parameters No need to specify result type new operator invoked with parameters matching those of some constructor If programmer provides no constructor, Java provides default constructor (no parameters) public class Point { private float x,y; public Point() { x=y=0; // same as default } public Point(float coordX, float coordY) { x=coordX; y=coordY; } public Point(float xy) { this(xy,xy); } Constructor chaining

Default Constructor Takes no parameters, initializes everything to defaults 0, null etc. Graciously provided by Java for absent- minded programmers ;-) Only exists if there are no explicitly defined constructors Any constructor, even one taking parameters, means no default

Overloading Multiple constructors is a prominent example of overloading Multiple methods can have same name but different signatures public class Point { private float x,y; public void move(float dx, float dy){ x+=dx; y+=dy; } public void move(float dxy){ move(dxy, dxy); }

Strings Strings in Java are objects of class java.lang.String Java.lang is a fundamental library String has a lot of nice features: check it out in the java API!

Turning objects into Strings All classes have a method toString() to provide a textual description of objects Can be (re-)defined wrt class logic public class Person {... public String toString() { String ret; ret = name + “ is tall ”; ret += height; ret += “ inches and weighs ”; ret += weight; ret += “ pounds.” return ret; }... }

Turning objects into Strings toString() can be invoked implicitlly When object is used within String manipulation operations Person assistant=new Person(“Mike”); System.out.println(“the assistant is: "+ assistant );

Summary Introduction to the Java language What is Java, what is a Java program Style, Javadocs Language basics Types, variables Classes, objects, arrays Visibility and encapsulation Some utilities String, toString() System.out