Objects and Classes CS 3250. The Building Blocks Classes: –Classes have variables and methods. –No global variables, nor global functions. –All methods.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
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.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Lecture 2: Object Oriented Programming I
PACKAGES. PACKAGES IN JAVA A package is a collection of related classes and interfaces in Java Packages help in logical grouping of classes and interfaces.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Memory Model of A Program, Methods Overview l Memory storage areas for an executing program l Introduction to methods and methods definitions l General.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
OOP Languages: Java vs C++
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Java and C++, The Difference An introduction Unit - 00.
1 Lecture 2: Object Oriented Programming in Java.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Programming in Java CSCI-2220 Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
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)
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.
Constructors & Garbage Collection Ch. 9 – Head First Java.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
1 Chapter 5: Defining Classes. 2 Basics of Classes An object is a member of a class type What is a class? Fields & Methods Types of variables: –Instance:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Packages. Access Specifications Public Available anywhere (public keyword) Only one public class per file allowed Protected Available in subclasses, and.
1 Chapter 6 Programming with Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
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
Variables in Java A variable holds either
JAVA MULTIPLE CHOICE QUESTION.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Inheritance-Basics.
Packages When we name a program , we name it by class name…
Java Basics Packages.
Computer Science II Exam 1 Review.
Overloading and Constructors
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
Interfaces.
Object Oriented Programming in java
Java Programming Language
Classes, Objects and Methods
Introduction to Object-Oriented Concepts in Java
Chapter 6 Objects and Classes
Interfaces,Packages and Threads
Classes and Objects Object Creation
Chapter 7 Objects and Classes
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Objects and Classes CS 3250

The Building Blocks Classes: –Classes have variables and methods. –No global variables, nor global functions. –All methods are defined inside classes (except native methods) Java class library, over 3,000 classes: –GUI, graphics, image, audio –I/O –Networking –Utilities: set, list, hash table

Organization of Java Programs Java provides mechanisms to organize large-scale programs in a logical and maintainable fashion. –Class --- highly cohesive functionalities –File --- one class or more closely related classes –Package --- a collection of related classes or packages

Organization of Java Programs The Java class library is organized into a number of packages: –java.awt --- GUI –java.io --- I/O –java.util --- utilities –java.applet --- applet –java.net --- networking See the online API documentation –link on class page

Objects and Object Variables Suppose you have the following line in your program: String word = "kryptonite"; What kind of thing is word ?

Objects and Object Variables Suppose you have the following line in your program: String word = "kryptonite"; What kind of thing is word ? Hint: It is not an object of class String.

Objects and Object Variables Suppose you have the following line in your program: String word = "kryptonite"; What kind of thing is word ? Answer: It is a variable that can refer to objects of class String.

Object References String word = "kryptonite"; Sometimes it is very important to understand how reference variables work, like in the following situations... "kryptonite" word instance of String

Null References String word; int length = word.length(); What will happen when this code executes? word

Aliases String word = "kryptonite"; String word2 = word; "kryptonite" word instance of String word2 Aliases of mutable objects can be tricky. Why?

Aliases bob.setSalary(50000); sue.setSalary(60000); bob sue salary ???

Variable, Object, Class, Type Variables have types, objects have classes. A variable is a storage location and has an associated type. An object is an instance of a class or an array. The type of a variable is determined at compilation time. The class of an object is determined at run time.

Variable, Object, Class, Type A variable in Java can be of: primitive type --- hold exact value reference type --- hold pointers to objects null reference: an invalid object object reference: pointer to an object whose class is assignment compatible with the type of the variable.

Reference Type and Garbage Collection All objects reside on the heap –Must use the new operator A “reference” is returned –More like a pointer than a C++ reference You can’t “delete” the object through its reference It is cleaned up by the garbage collector –After the object is no longer used –When the GC is good and ready to do it! –Memory leaks are practically non-existent in Java

[ClassModifiers] class ClassName [ extends SuperClass] [ implements Interface 1, Interface 2...] { ClassMemberDeclarations } public class MapDisplay extends JPanel implements MouseListener, KeyListener {... } Class Declaration

public Accessible everywhere One public class allowed per file. The file must be named ClassName.java private Only accessible within the class Accessible within the current class package. abstract A class that contains abstract methods final No subclasses Class Modifiers

[MethodModifiers] Type Name ( [ParameterList] ) { Statements } public static void main(String[] args) { System.out.println ("Red alert, shields up!"); } [FieldModifiers] Type FieldName 1 [ = Initializer 1 ], FieldName 2 [ = Initializer 2 ]...; private final int MAX_SPEED = 60; Method And Field Declaration

For both methods and fields: public protected private static final Final methods cannot be overridden For methods only: abstract synchronized native For fields only: volatile transient Method and Field Modifiers

public class Point { public int x, y; public void move(int dx, int dy) { x += dx; y += dy; } Point point1; // Point not created Point point2 = new Point(); point1 = point2; point1 = null; x and y are initialized to their default initial values. Class Declaration Example

public class Point { public int x = 0, y = 0; public void move(int dx, int dy) { x += dx; y += dy; } Point point1 = new Point(); // (0,0) Explicit Initializer

Constructors Constructors are invoked after default initial values are assigned. No-arg constructor is provided as a default when no other constructors are provided. public class Point { public int x, y; public Point() { // no-arg x = 0; y = 0; } public Point(int x0, int y0) { x = x0; y = y0; } Point point1 = new Point(); // no-arg Point point2 = new Point(20, 20);

Initialization Block 1.Data fields initialized to default value (0, false, or null) 2.Field initializers and initialization blocks are executed in order they appear 3.If first line of constructor calls another constructor, that other constructor is executed. 4.The body of the constructor is executed. public class Point { public int x, y; // Object initialization block // Executes before constructor { x = 0; y = 0; }

Object Reference: this You can use this inside a method, It refers to the current object on which the method is invoked. It's commonly used to pass the object itself as a parameter aList.insert(this);

Object Reference: this It can also be used to access hidden variables: public class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } It can also be used to call other constructors

Wrappers Objects that hold primitives –Read-only! Used when objects are called for –In collections, for example More expensive than using primitives Have symbolic constants for min/max, conversion functions to primitives Example: Primitives.java, Wrappers.java –Compares time with primitives to time with wrappers

Static variable or fields: one per class, rather than one per object. Static variables are also known as class variables. –Initialized when the class is loaded by the JVM Non-static variables are called instance variables. class IDCard { public long id; protected static long nextID = 0; public IDCard() { id = nextID++; } Static Variables

class IDCard { public long id; protected static long nextID = 0;... public static void skipID() { nextID++; } Static Methods A static method can only access static variables and invoke other static methods –(unless an object reference is used) can not use this reference

IDCard.skipID(); // the preferred way IDCard mycard = new IDCard(); mycard.skipID(); Invoking Methods Non-static methods must be invoked through an object reference: object_reference.method(parameters) Static methods can be invoked through an object reference or the class name: class_name.method(parameters) So, you can do either of the following: Why is this way preferred?

Passing Parameters All parameters are passed by value: A copy of the parameter will always be made, but never a copy of an object. Why not? doSales(bob, 2005); void doSales(Employee emp1, int year) { String name = emp1.getName(); int sales = emp1.getSales(year); emp1.setCommission(sales * pct); }

bob emp1 commission Passing Parameters doSales(bob, reportYear); void doSales(Employee emp1, int year) { String name = emp1.getName(); int sales = emp1.getSales(year); emp1.setCommission(sales * pct); } ??? 2005 year reportYear

final "variables" Final variables are named constants. class CircleStuff { static final double pi =3.1416; } Final parameters are useless.

Blank finals Allows you to declare a final without initializing it Applies to fields as well as local vars Must still be initialized before it’s used: class MyClass { final String s; MyClass(String s) { this.s = s; } Can not be initialized after construction.

The toString() method converts objects to strings. public class Point { public int x, y;... public String toString() { return "(" + x + "," + y + ")"; } Then, you can do Point p = new Point(10,20); System.out.println("A point at " + p); // Output: A point at (10,20) The toString() Method

Access Specifications Public –Available anywhere ( public keyword) –Only one public class per file allowed Protected –Available in subclasses, and in the package –protected keyword Package (“Friendly”) –Available in the package only –No access specifier Private –Available in class only ( private keyword)

What’s a Package? A set of classes (.class files) in the same directory –Similar to C++ namespaces –Don’t have to use import –A “substitute” for friend in C++ The directory must match the package name –Can have multiple segments (dot-separated) –java.util corresponds (loosely) to the subdirectory java/util Use the package keyword –Must be first non-comment line of file

The Class Path A search path Consists of directories or JAR files All package directories must be subdirectories of a directory in the class path -classpath option CLASSPATH environment variable

The Unnamed Package The “default” package All classes not in a named package are in this package –Can span multiple directories –Uses the classpath

JAR Files “Java Archive” A way of collecting/compressing.class files jar –cf myJar.jar *.class For faster loading of applets And for distributing pre-compiled software Uses ZIP format Can run from command-line with the “java” command java –jar myJar.jar