notes java ds

Upload: rguptamtech

Post on 08-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Notes Java DS

    1/7

    THE LANGUAGE OF OBJECT -ORIENTED PROGRAMMING===========================================Object: An object is a repository of data.

    For example, if MyList is aShoppingList object, MyList might record...your shopping list.

    Class: A class is a type of object.Many objects of the same class might exist; for instance, MyList andYourList may both be shopping lists.

    Method: A procedure or function that operates on an object or a class.A method is associated with a partic ular class.

    For instance, addItem might be a method that adds an item to anyShoppingList object. Sometimes a method is associated with a familyof classes. For instance, addItem might operate on any List, ofwhich a ShoppingList is just one type.

    Inheritance: A class may inherit properties from a more general class.

    Forexample, the ShoppingList class inherits from the List class the

    property of storing a sequence of items.

    Polymorphism: The ability to have one method call work on severaldifferent classes of objects, even if those classes need differentimplementations o f the method call.

    For example, one line of code might be able to call the"addItem" method on _every_ kind of List, even though adding an

    item to aShoppingList is completely different from adding an item to a

    ShoppingCart.

    Object-Oriented: Each object knows its own class and which methodsmanipulate objects in that class.

    Each ShoppingList and each ShoppingCart knows whichimplementation of addItem applies to it.

    In this list, the one thing that truly distinguishes object -orientedlanguages from procedural languages (C, Fortran, Basic, Pascal) ispolymorphism.

    Java----Java allows you to store data in variables, but first you must _declare_themand specify their _type_.

    Scheme: (let ((x 1)) ) Java: int x;x = 1;

    This declaration does two things.(1) It allocates a chunk of memory big enough to store an integer, which

  • 8/6/2019 Notes Java DS

    2/7

    Java calls type "int".(2) It names the variable (chunk of memory) "x".

    Variables are used not just to store numbers, but also to _reference_objects.

    There are two ways to get classes of objects to play with:

    (1) Use one defined by somebody else. Java has tons of pre -definedclasses you can use. Many come in the "Java standard library" providedwith everyJava compiler.(2) Define your own.

    For example, Java has a built-in class called String.

    String myString;

    This does _not_ create a String object. Instead, it declares a variable(chunk of memory) that can store a _reference_ to a String object.

    I draw it as abox.

    ---myString | | < -- This box is a variable (not an

    object).---

    Initially, myString doesn't reference anything. You can make it referencea String object by writing an assignment statement. But how do we getahold of an actual String o bject? You can create one.

    myString = new String();

    This line performs two distinct steps. First, the phrase "new String()" iscalled a _constructor_. It constructs a brand new String object. Second,theassignment "=" causes myString to _reference_ the object. You can think ofthis as myString pointing to the object.

    --- ------myString |.+---->| | a String object

    --- ------

    Unlike Scheme and Matlab, Java programs must be compiled before you can r unthem. _Compilation_ converts your written code to a machine -readablebytecode.The advantage is a faster program than one written in Scheme. The

    disadvantageis that you have to wait for it to compile.

    Scheme Java------ ----

    Scheme program (.scm) Java program (.java)| || eval | javacv v

    Answer .class files|

  • 8/6/2019 Notes Java DS

    3/7

    | javav

    Answer

    Postscript: Anatomy of a Sm all Java Program (for discussion section)--------------------------------------------

    Assume the following code is in a file called HelloWorld.java:

    class HelloWorld {public static void main (String[] args) {

    System.out.println("Hello, world");}

    }

    The classes are "HelloWorld", "String", and "System".

    The objects are "args", "System.out", and the string "Hello, world".(Actually, the first two of these are _references_ to objects.)

    The methods are "main" and "println". The println method prints itsparameter,and the main method prints the string "Hello, world".

    Let's look at the innermost line first; it does all the action. "out"references an object whose class is PrintStream. A PrintStream is a pathby which characters can be output by a program. The characters that aresent through "out" find their way to your computer screen.

    System is a class which happens to contain the variable out (among manyother variables). We have to write "System.out" to ad dress the outputstream, because other classes might have variables called "out" too, withtheir own meanings.

    "println" is a method (procedure) of the class PrintStream. Hence, we caninvoke "println" from any PrintStream object, including System.out.

    "println"takes one parameter, which can be a string.

    "main" is a method in the "HelloWorld" class. The HelloWorld class knowshowto do the "main" operation, just like the PrintStream class knows how to dothe"println" operation.

    ------------------------------------------ ---------------------- | || | | | | || --- | | println (method) | | || out |.+-----+-->| | | || --- | | | | main (method) |

    --System (class)-- --An object of class-- | |PrintStream | |---HelloWorld (class)---

    The classes System and PrintStream are all automatically provided for youbyany Java compiler. Somebody has programmed them for you, so that you don'thave to figure out for yourself how to send characters to the terminal.

  • 8/6/2019 Notes Java DS

    4/7

    OBJECTS AND CONSTRUCTORS

    String s1; // Step 1: declare a String variable.s1 = new String(); // Step 2: assi gn it a value: a new emptystring.String s2 = new String(); // Steps 1 & 2 combined.

    At this point, s1 and s2 are both --- ------ --- ------variables that reference empty strings. s1 |.+ ---->| | s2 |.+---->||

    --- ------ --- ------

    s1 = "Yow!"; // Construct a new String; make s1 a reference toit.

    --- ----------s1 |.+---->| Yow! |

    --- ----------

    s2 = s1; // Assign s2 the value of s1.

    --- ---------- ---s1 |.+---->| Yow! |

  • 8/6/2019 Notes Java DS

    5/7

    Observe that "new String()" can take no parameters, or one parameter.Theseare two different constructor s--one that is called by "new String()", andonethat is called by "new String(s1)". (Actually, there are many more thantwo--check out the online Java API to see all the possibilities.)

    METHODS=======Let's look at some methods that aren't constructors .

    s2 = s1.toUppercase(); // Create a string like s1, but in all uppercase.

    --- ----------s2 |.+---->| YOW! |

    --- ----------

    String s3 = s2.concat("!!"); // Also written: s3 = s2 + "!!";

    --- ------------s3 |.+---->| YOW!!! |

    --- ------------

    String s4 = "*".concat(s2).concat("*"); // Also written: s4 = "*" + s1 +"*";

    --- ------------s4 |.+---->| *YOW!* |

    --- ------------

    Now, here's an important fact: when Java executed the line

    s2 = s1.toUppercase();

    the String object "Yow!" did _not_ change. Instead, s2 itself changed to

    reference a new object. Java wrote a new "pointer" into the variable s2,sonow s2 points to a different object than it did before.

    Unlike in C, in Java Strings are _immutable_ --once they've beenconstructed,their contents never change. If you want to change a String object, you'vegotto create a brand new String object that reflects the changes you want.Thisis not true of all objects; most Java objects let you change theircontents.

    I/O Classes and Objects in Java

    -------------------------------Here are some objects in the System class for interacting with a user:

    System.out is a PrintStream object that outputs to the screen.System.in is an InputStream object that reads from the keyboard.

    [Reminder: this is shorthand for "System.in is a variable thatreferences

    an InputStream object."]

    But System.in doesn't have methods to read a line directly. There is amethod

  • 8/6/2019 Notes Java DS

    6/7

    called readLine that does, but it is defined on BufferedReader objects.

    - How do we construct a BufferedReader? One way is with anInputStreamReader.- How do we construct an InputStreamReader? We need an InputStream.- How do we construct an InputStrea m? System.in is one.(You can figure all of this out by looking at the constructors in the

    onlineJava libraries API--specifically, in the java.io library.)

    Why all this fuss?

    InputStream objects (like System.in) read raw data from some source (likethekeyboard), but don't format the data.

    InputStreamReader objects compose the raw data into characters (which aretypically two bytes long in Java).

    BufferedReader objects compose the characters into entire lines of text.

    Why are these tasks divided amon g three different classes? So that any one

    task can be reimplemented (say, for improved speed) without changing theothertwo.

    Here's a complete Java program that reads a line from the keyboard andprintsit on the screen.

    import java.io.*;

    class SimpleIO {public static void main(String[] arg) throws Exception {

    BufferedReader keybd =new BufferedReader(new InputStreamReader(System.in));

    System.out.println(keybd.readLine());}

    }

    Don't worry if you don't understand the first three lines; we'll learn theunderlying ideas eventually. The first line is present because to use theJavalibraries, other than java.lang, you need to "import" them. java.ioincludesthe InputStreamReader and BufferedReader classes.

    The second line just gives the program a name, "SimpleIO".

    The third line is present because any Java program always begins execution

    at amethod named "main", which is usually defined more or less as above. Whenyouwrite a Java program, just copy the line of code, and p lan to understand itafew weeks from now.

    Classes for Web Access----------------------Let's say we want to read a line of text from the White House Web page.(The

  • 8/6/2019 Notes Java DS

    7/7

    line will be HTML, which looks ugly. You don't need to understand HTML.)

    How to read a line of text? With readLine on BufferedReader.How to create a BufferedReader? With an InputStreamReader.How to create a InputStreamReader? With an InputStream.How to create an InputStream? With a URL.

    import java.net.*;import java.io.*;

    class WHWWW {public static void main(String[] arg) throws Exception {

    URL u = new URL("http://www.whitehouse.gov/");InputStream ins = u.openStream();InputStreamReader isr = new InputStreamReader(ins);BufferedReader whiteHouse = new Buffere dReader(isr);System.out.println(whiteHouse.readLine());

    }}

    Postscript: Object -Oriented Terminology (not examinable)----------------------------------------

    In the words of Turing Award winner Nicklaus Wirth, "Object -orientedprogramming (OOP) solidly rests on the principles and concepts oftraditionalprocedural programming. OOP has not added a single novel concept ... alongwith the OOP paradigm came an entirely new terminology with the purpose ofmystifying the roots of OOP." Here's a transla tion guide.

    Procedural Programming Object -Oriented Programming---------------------- ---------------------------record / structure objectrecord type classextending a type declaring a subclassprocedure methodprocedure call sending a message to the method [ack!

    phthhht!]

    I won't ever talk about "sending a message" in this class. I think it's acompletely misleading metaphor. In computer science, message -passingnormallyimplies asynchrony: that is, the process that sends a message can continueexecuting while the receiving process receives the message and acts on it.Butthat's NOT what it means in object -oriented programming: when a Javamethod"sends a message" to an other method, the former method is frozen until thelatter methods completes execution, just like with procedure calls in mostlanguages. But you should probably know about this termology, much as itsucks, because you'll probably run into it sooner or la ter.