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

Java Methods & Classes

This document provides an overview of Java methods and classes. It discusses Java's primitive data types, classes as object definitions, built-in classes like String and Math, the three principles of object-oriented programming (encapsulation, inheritance, polymorphism), how classes and objects are defined and used, variable scope, the this reference, visibility modifiers like public and private, using objects by accessing other class methods and fields, API documentation generation with javadoc, and basic input/output stream classes for file manipulation in Java.

Uploaded by

sansayana
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

Java Methods & Classes

This document provides an overview of Java methods and classes. It discusses Java's primitive data types, classes as object definitions, built-in classes like String and Math, the three principles of object-oriented programming (encapsulation, inheritance, polymorphism), how classes and objects are defined and used, variable scope, the this reference, visibility modifiers like public and private, using objects by accessing other class methods and fields, API documentation generation with javadoc, and basic input/output stream classes for file manipulation in Java.

Uploaded by

sansayana
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

Java Methods & Classes

Primitive Data Types


Data type byte short int long float -128 .. 127 (8 bits) -32,768 .. 32,767 (16 bits) -2,147,483,648 .. 2,147,483,647 (32 bits) -9,223,372,036,854,775,808 .. ... (64 bits) +/-10-38 to +/-10+38 and 0, about 6 digits precision Range of values

double
char boolean

+/-10-308 to +/-10+308 and 0, about 15 digits precision


Unicode characters (generally 16 bits per char) True or false

Classes ARE Object Definitions


OOP - object oriented programming code built from objects Java these are called classes Each class definition is coded in a separate .java file Name of the object must match the class/object name

Built in Classes

Java has a large built in library of classes with lots of useful methods Ones you should become familiar with quickly String Math Integer, Character, Double

System Arrays Scanner File Object Random Look at the Java API page

The three principles of OOP

Encapsulation
Objects hide their functions (methods) and data (instance variables)

Inheritance
Each subclass inherits all variables of its manual superclass

car

Super class
automatic

Subclasses

Polymorphism
Interface same despite draw() different data types

draw()

Classes and Objects


A Java program consists of one or more classes A class is an abstract description of objects Here is an example class:

class Dog { ...description of a dog goes here... }

Here are some objects of that class:

More Objects

Here is another example of a class:


class Window { ... }

Here are some examples of Windows:

Classes contain data definitions

Classes describe the data held by each of its objects Data usually goes first in a class Example:
class Dog { String name; int age; ...rest of the class... } A class may describe any number of objects
Examples: "Fido", 3; "Rover", 5; "Spot", 3;

A class may describe a single object, or even no objects at all

Classes contain methods


A class may contain methods that describe the behavior of objects Methods usually go after the data Example:
class Dog { ... void bark() { System.out.println("Woof!"); } }

When we ask a particular Dog to bark, it says Woof! Only Dog objects can bark; the class Dog cannot bark

Methods contain statements

A statement causes the object to do something


(A better word would be commandbut it isnt)

Example:
System.out.println("Woof!"); This causes the particular Dog to print (actually, display on the screen) the characters Woof!

Methods may contain temporary data

Data described in a class exists in all objects of that class


Example: Every Dog has its own name and age

A method may contain local temporary data that exists only until the method finishes Example:

void wakeTheNeighbors( ) { int i = 50; // i is a temporary variable while (i > 0) { bark( ); i = i 1; } }

Classes always contain constructors


A constructor is a piece of code that constructs, or creates, a new object of that class If you dont write a constructor, Java defines one for you (behind the scenes) You can write your own constructors Example: (This part is the constructor) class Dog {
String name; int age; Dog(String n, int age) { name = n; this.age = age; } }

Variable Scope

Variables may be declared in: Class state variables Method/constructor local variables (and parameters) Inner block of a method also local variables A variable is recognized throughout the block in which it was defined. This is called the scope of the variable. Local variables are allocated when the method is entered and freed when the method exits. The same name may be used in different scopes, and refer to totally different things If the same name is used in an outer and inner scope, then the inner scope definition hides the outer one.

The this reference

When appearing inside an instance method, the this keyword denotes a reference to the object that the method is acting upon. The following are equivalent:
public int getHours() { return hours; } public int getHours() { return this.hours; }

Visibility Modifiers

We accomplish encapsulation through the appropriate use of visibility modifiers Visibility modifiers specify which parts of the program may see and use any particular class/method/field Information hiding is good! A modifier is a Java reserved word that specifies particular characteristics of a programming construct We've used the modifier final to define a constant Java has three visibility modifiers: public, private, and protected We will discuss the protected modifier later in the course

Public/private

Methods/data may be declared public or private meaning they may or may not be accessed by code in other classes Good practice:
keep data private keep most methods private

well-defined interface between classes helps to eliminate errors

Situation Accessible to class from same package?

public yes

protected yes

default yes

private no

Accessible to class from different package?

yes

no, unless it is a subclass

no

no

Using objects

Here, code in one class creates an instance of another class and does something with it
Fruit plum=new Fruit(); int cals; cals = plum.total_calories();

Dot operator allows you to access (public) data/methods inside Fruit class

API Documentation

Your classes are often intended to be used by other programmers Programmers that use your class are not interested in the way it is implemented. They want to use it as a whole and are only interested in what it does and how to use it. API (Application Programmer Interface) documentation is a description of the interface of the class intended for the application programmer who wants to use it. To use the class, we need not (and should not) look at the code. All that is needed is the class API.

API Documentation

The JDK contains a special tool for the generation of API documentation for your classes, called javadoc. Any documentation which is part of the interface begins with /** (double asterick) and ends with */ javadoc takes as input Java programs and automatically generates documentation using: the public/protected method signatures the documentation comments (enclosed by /** */). The output is an HTML file which can be viewed by an internet browser.

Clock API Documentation


/** * A clock represents a point of time in a 12 * hour period within a precision of seconds. * Its range: 1:00:00 -- 12:59:59. */ public class Clock { private int hours; private int minutes; private int seconds; /** * Constructs a Clock: Sets the clock to the * specified time. */ public Clock(int hours, int minutes, int seconds){ // }

Clock API Documentation /** cont. a Clock: Sets the clock to 12:00:00 * Constructs
*/ public Clock(){ this(12,0,0); }

/** * Advances this clock by 1 second. */ public void secondElapsed() { // }


//

Javadoc Process
.java file

javadoc

.html file

View using a

browser

Clock javadoc - page 1

Clock javadoc - page 2

What should you comment?

You should put a documentation comment for the class itself and for any member of the class which is part of its interface. All public constructors and methods should have documentation comments. Private methods are not part of the interface of the class, thus javadoc skips them. (But you should still comment them for internal purposes.) In the rare cases that there are public fields, they should have documentation comments.

API Documentation

Remember that documentation comments are written for programmers who use your class as a whole. They should describe only What the class does, How to use it. Documentation comments should not describe how a class is implemented. Documentation comments should be Short and descriptive, Written in a simple language (ENGLISH), Accurate. Assume that the reader doesnt know anything about your class

API Documentation Tags

Documentation comments can also include tagged paragraphs that give a standard way to document several features of the interface such as method parameters, return values, etc. A tagged paragraph begins with the symbol @ followed with a tag keywords. Tags: @see, @author, @version, @param, @return, @exception.

Documentation comments text can include HTML tags.

@param tag
/** * Changes the current time to hour:minute:second * @param hours The new hour value. * @param minutes The new minutes value. * @param seconds The new seconds value. */ public void setTime(int hours, int minutes, int seconds) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; }

setTime generated javadoc

@return
/** * Returns the current hour * @return The current hour (between 1 and 12). */ public void getHour() {
return hours; }

getHour javadoc

Java Development Kit tools


javac - The Java Compiler java - The Java Interpreter jdb The Java Debugger appletviewer -Tool to run the applets

javap - to print the Java bytecodes javaprof - Java profiler javadoc - documentation generator javah - creates C header files

Stream Manipulation

Streams and I/O

basic classes for file IO


FileInputStream, for reading from a file FileOutputStream, for writing to a file

Example:

Open a file "myfile.txt" for reading FileInputStream fis = new FileInputStream("myfile.txt"); Open a file "outfile.txt" for writing FileOutputStream fos = new FileOutputStream ("myfile.txt");

35

Display File Contents


import java.io.*; public class FileToOut1 { public static void main(String args[]) { try { FileInputStream infile = new FileInputStream("testfile.txt"); byte buffer[] = new byte[50]; int nBytesRead; do { nBytesRead = infile.read(buffer); System.out.write(buffer, 0, nBytesRead); } while (nBytesRead == buffer.length); } catch (FileNotFoundException e) { System.err.println("File not found"); } catch (IOException e) { System.err.println("Read failed"); } } }

36

Filters
Once a stream (e.g., file) has been opened, we can attach filters Filters make reading/writing more efficient Most popular filters: For basic types: DataInputStream, DataOutputStream For objects: ObjectInputStream, ObjectOutputStream

37

Writing data to a file using Filters


import java.io.*; public class GenerateData { public static void main(String args[]) { try { FileOutputStream fos = new FileOutputStream("stuff.dat"); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(2); dos.writeDouble(2.7182818284590451); dos.writeDouble(3.1415926535); dos.close(); fos.close(); } catch (FileNotFoundException e) { System.err.println("File not found"); } catch (IOException e) { System.err.println("Read or write failed"); } } }

38

Reading data from a file using filters


import java.io.*; public class ReadData { public static void main(String args[]) { try { FileInputStream fis = new FileInputStream("stuff.dat"); DataInputStream dis = new DataInputStream(fis); int n = dis.readInt(); System.out.println(n); for( int i = 0; i < n; i++ ) { System.out.println(dis.readDouble()); } dis.close(); fis.close(); } catch (FileNotFoundException e) { System.err.println("File not found"); } catch (IOException e) { System.err.println("Read or write failed"); } } 39 }

Object serialization
Write objects to a file, instead of writing primitive types.
Use the ObjectInputStream, ObjectOutputStream classes, the same way that filters are used.

40

Write an object to a file


import java.io.*; import java.util.*; public class WriteDate { public WriteDate () { Date d = new Date(); try { FileOutputStream f = new FileOutputStream("date.ser"); ObjectOutputStream s = new ObjectOutputStream (f); s.writeObject (d); s.close (); } catch (IOException e) { e.printStackTrace(); }
public static void main (String args[]) { new WriteDate (); } }
41

Read an object from a file


import java.util.*; public class ReadDate { public ReadDate () { Date d = null; ObjectInputStream s = null; try { FileInputStream f = new FileInputStream ("date.ser"); s = new ObjectInputStream (f); } catch (IOException e) { e.printStackTrace(); } try { d = (Date)s.readObject (); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvalidClassException e) { e.printStackTrace(); } catch (StreamCorruptedException e) { e.printStackTrace(); } catch (OptionalDataException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println ("Date serialized at: "+ d); } public static void main (String args[]) { new ReadDate (); } }

42

You might also like