1 Lecture 2: Object Oriented Programming in Java.

Slides:



Advertisements
Similar presentations
Packages Sudhir Talasila Preeti Navale. Introduction Packages are nothing more than the way we organize files into different directories according to.
Advertisements

Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Lecture 2: Object Oriented Programming I
Road Map Introduction to object oriented programming. Classes
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
Unit 051 Packages What is a Package? Why use Packages? Creating a Package Naming a Package Using Package Members Managing Source and Class Files Visibility.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
OOP Languages: Java vs C++
Access Control Problem A primary consideration in object- oriented design is to “separate the things that change from the things that stay.
Java Programming, Second Edition Chapter Four Advanced Object Concepts.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA ‏ Packages.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
More Object Concepts Chapter 4.  Our class is made up of several students and each student has a name and test grades  How do we assign the variables.
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.
CSC Programming I Lecture 8 September 9, 2002.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
EE2E1. JAVA Programming Lecture 3 Java Programs and Packages.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
Programming in Java CSCI-2220 Object Oriented Programming.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Class Libraries Chapter 1 1 Source Intro to Java Programming Y. Daniel Liang.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
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 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved 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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Packages. The main feature of OOP is its ability to support the reuse of code: –Extending the classes –Extending interfaces The features in basic form.
Methods. Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Object Oriented Programming Object and Classes Lecture 3 MBY.
Java Packages - allow you to group classes as a collection Standard Java library has packages: java.lang and java.util … Also hierarchical: java and javax.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
JAVA MULTIPLE CHOICE QUESTION.
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Object Oriented Systems Lecture 03 Method
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Java Programming Language
Packages and Interfaces
Object Oriented Programming in java
Applying OO Concepts Using Java
Object Oriented Programming in java
Chapter 7 Objects and Classes
Presentation transcript:

1 Lecture 2: Object Oriented Programming in Java

2 Object Creation Body sun = new Body( ); An object is created by the new method The runtime system will allocate enough memory to store the new object If no enough space, the automatic garbage collector will reclaim space from other no longer used objects. If there is still no enough space, then an OutOfMemoryError exception will be thrown No need to delete explicitly define a variable sun to refer to a Body object create a new Body object class Body { private long idNum; private String name = “empty”; private Body orbits; private static long nextID = 0; }

3 Constructor constructor is a way to initialize an object before the reference to the object is returned by new has the same name as the class can have any of the same access modifiers as class members similar to methods. A class can have multiple constructors as long as they have different parameter list. Constructors have NO return type. Constructors with no arguments are called no-arg constructors. If no constructor is provided explicitly by the programmer, then the language provides a default no-arg constructor which sets all the fields which has no initialization to be their default values. It has the same accessibility as its class.

4 Sample Class and Constructors class Body { private long idNum; private String name= “empty”; private Body orbits; private static long nextID = 0; Body( ) { idNum = nextID++; } Body(String bodyName, Body orbitsAround) { this( ); name = bodyName; orbits = orbitsAround; } Assume no any Body object is Assume no any Body object is constructed before: constructed before: Body sun = new Body( );Body sun = new Body(“Sol”, null); Body earth = new Body(“Earth”, sun); idNum: name: orbits: sun nextID = idNum: name: orbits: sun nextID = idNum: name: orbits: earth nextID = 0 empty null 1 0 Sol null 1 Earth sun 12

5 Usage of this inside a constructor, you can use this to invoke another constructor in the same class. This is called explicit constructor invocation. It MUST be the first statement in the constructor body if exists. this can also be used as a reference of the current object. It CANNOT be used in a static method

6 Example: usage of this as a reference of the current object class Body { private long idNum; private String name; private Body orbits; private static long nextID = 0; private static LinkedList bodyList = new LinkedList();... Body(String name, Body orbits) { this.name = name; this.orbits = orbits; }... private void inQueue() { bodyList.add(this); }... }

7 Without initialization block class Body { private long idNum; private String name = “noNameYet”; private Body orbits; private static long nextID = 0; Body( ) { idNum = nextID++; } Body(String bodyName, Body orbitsAround) { this( ); name = bodyName; orbits = orbitsAround; } With initialization block class Body { private long idNum; private String name = “noNameYet”; private Body orbits; private static long nextID = 0; { idNum = nextID++; } Body(String bodyName, Body orbitsAround) { name = bodyName; orbits = orbitsAround; } Other initialization methods(1) Initialization block  a block of statements to initialize the fields of the object  outside of any member or constructor declaration  they are executed BEFORE the body of the constructors!

8 Other initialization methods(2) Static initialization block  Resembles a non-static initialization block except that it is declared static, can only refer to static members and cannot throw any checked exceptions  Gets executed when the class is first loaded Example class Primes { static int[] primes = new int[4]; static { primes[0] = 2; for(int i=1; i<primes.length; i++) { primes[i] = nextPrime( ); } //declaration of nextPrime( )... }

9 Packages Classes can be grouped in a collection called package Java’s standard library consists of hierarchical packages, such as java.lang and java.util Main reason to use package is to guarantee the uniqueness of class names  classes with same names can be encapsulated in different packages  tradition of package name: reverse of the company’s Internet domain name e.g. hostname.com -> com.hostname

10 Class importation (1) Two ways of accessing PUBLIC classes of another package 1)explicitly give the full package name before the class name.  E.g. java.util.Date today = new java.util.Date( ); 2)import the package by using the import statement at the top of your source files (but below package statements). No need to give package name any more.  to import a single class from the java.util package import java.util.Date; Date today = new Date( );  to import all the public classes from the java.util package import java.util.*; Date today = new Date( );  * is used to import classes at the current package level. It will NOT import classes in a sub-package.

11 Sample class: import javax.swing.*; public class SampleClass { MenuEvent c; } %> javac SampleClass.java MenuEvent is a class in the package javax.swing.event, which locates in the package javax.swing. You need this statement: import javax.swing.event.*; SampleClass.java:4: cannot find symbol Symbol : class MenuEvent Location: class SampleClass MenuEvent c; ^ 1 error

12 Class importation (2) What if you have a name conflict? E.g import java.util.*; import java.sql.*; Date today = new Date( );//ERROR:java.util.Date //or java.sql.Date?  if you only need to refer to one of them, import that class explicitly import java.util.*; import java.sql.*; import java.util.Date; Date today = new Date( ); // java.util.Date  if you need to refer to both of them, you have to use the full package name before the class name import java.util.*; import java.sql.*; java.sql.Date today = new java.sql.Date( ); java.util.Date nextDay = new java.util.Date( );

13 See this code: import java.lang.Math; public class importTest { double x = sqrt(1.44); } Compile: %> javac importTest.java importTest.java:3: cannot find symbol symbol : method sqrt(double) location: class importTest double x = sqrt(1.44); ^ 1 error ? For the static members, you need to refer them as className.memberName

14 Static importation In J2SE 5.0, importation can also be applied on static fields and methods, not just classes. You can directly refer to them after the static importation.  E.g. import all static fields and methods of the Math class import static java.lang.Math.*; double x = PI;  E.g. import a specific field or method import static java.lang.Math.abs; double x = abs(-1.0); Any version before J2SE 5.0 does NOT have this feature!

15 Encapsulation of classes into a package Add a class into a package — two steps: 1.put the name of the package at the top of your source file 2.put the files in a package into a subdirectory which matches the full package name stored in the file “Employee.java” which is stored under “somePath/com/hostname/corejava/” package com.hostname.corejava; public class Employee {... }

16 To emphasize on data encapsulation (1) Let’s see a sample class first public class Body { public long idNum; public String name = “ ”; public Body orbits = null; public static long nextID = 0; Body( ) { idNum = nextID++; } Body(String bodyName, Body orbitsAround) { this( ); name = bodyName; orbits = orbitsAround; } Problem: all the fields are exposed to change by everybody

17 To emphasize on data encapsulation (2) improvement on the previous sample class with data encapsulation public class Body { private long idNum; private String name = “ ”; private Body orbits = null; private static long nextID = 0; Body( ) { idNum = nextID++; } Body(String bodyName, Body orbitsAround) { this( ); name = bodyName; orbits = orbitsAround; } Problem: but how can you access the fields?

18 To emphasize on data encapsulation (3) improvement on the previous sample class with accessor methods public class Body { private long idNum; private String name = “ ”; private Body orbits = null; private static long nextID = 0; Body( ) { idNum = nextID++; } Body(String bodyName, Body orbitsAround) { this( ); name = bodyName; orbits = orbitsAround; } public long getID() {return idNum;} public String getName() {return name;}; public Body getOrbits() {return orbits;} } Note: now the fields idNum, name and orbits are read-only outside the class. Methods that access internal data are called accessor methods sometime

19 To emphasize on data encapsulation (4) modification on the previous sample class with methods setting fields class Body { private long idNum; private String name = “ ”; private Body orbits = null; private static long nextID = 0; // constructors omitted for space problem... public long getID() {return idNum;} public String getName() {return name;}; public Body getOrbits() {return orbits;} public void setName(String newName) {name = newName;} public void setOrbits(Body orbitsAround) {orbits = orbitsAround;} } Note: now users can set the name and orbits fields. But idNum is still read-only  Making fields private and adding methods to access and set them enables the users adding actions in the future  Don’t forget the private modifier on a data field when necessary! The default access modifier for fields is package

20 How the virtual machine located classes? How to tell the java virtual machine where to find the.class files? Answer: set the class path. Class path is the collection of all directories and archive files that are starting points for locating classes. E.g. - first suppose the following is the current classpath: /home/user/classdir:.:/home/user/archives/archive.jar - then suppose the interpreter is searching for the class file of the com.horstmann.corejava.Employee class. It will first search class in the system class files that are stored in archives in the jre/lib and jre/lib/ext directories. It can’t find the class there, so it will turn to search whether the following files exist in the following order: 1) /home/user/classdir/com/horstmann.corejava/Employee.class 2)./com/horstmann.corejava/Employee.class 3) com/horstmann/corejava/Employee.class inside /home/user/archives/archive.jar - if any of them is been found, then the interpreter stops searching process

21 Setting the class path Tedious way: set the class path with the -classpath option for the javac program javac –classpath /home/user/classdir:.:/home/user/archives/archive.jar MyProg.java (in Windows, use semicolon to separate the items of the class path) Set the CLASSPATH environment variable in a permanent way  UNIX/Linux If you use the C shell, add a line such as the following to the.cshrc file in your home directory setenv CLASSPATH /home/user/classdir:. If you use bash, add a line such as the following to the.bashrc or.bash_profile file in your home directory CLASSPATH=$CLASSPATH:.: /home/user/classdir export CLASSPATH after you save the modified files, run the command source.bashrc(or.cshrc or.bash_profile)  Windows NT/2000/XP Open the control panel, then open the System icon and select the Environment tab. Add a new environment variable named CLASSPATH and specify its value, or edit the variable if it exists already.

22 Naming conventions Package names: start with lowercase letter  E.g.java.util, java.net, java.io... Class names: start with uppercase letter  E.g.File, Math...  avoid name conflicts with packages  avoid name conflicts with standard keywords in java system Variable, field and method names: start with lowercase letter  E.g.x, out, abs... Constant names: all uppercase letters  E.g.PI... Multi-word names: capitalize the first letter of each word after the first one  E.g.HelloWorldApp, getName... Exception class names: (1) start with uppercase letter (2) end with “Exception” with normal exception and “Error” with fatal exception  E.g.OutOfMemoryError, FileNotFoundException

23 Supplemental reading Object-Oriented Programming Concepts Object and Classes in Java