Pages

May 30, 2015

[CS61B] Notes for class 1-Using objects



Object: A repository of data.

Class: Type of object.

Method: Procedure or function that operates on an object.
e.g. addItem: adds an item to any ShoppingList object

Inheritance: A class may inherit properties from a more general class.
e.g. ShoppingList inherits from List the property of storing a sequence of items.

Polymorphism: One method works on several classes; even if the classes need different implementations.
e.g. "addItem" method on every kind of List, though adding item to a ShoppingList is different from a ShoppingCart.

Object-Oriented: Each object knows its own class and methods.
e.g. Each ShoppingList and ShoppingCart knows which implementation applies to it.


Java
Variables: You must declare them and their type.
Variables also used to reference objects.

e.g.
String myString; 
//Only declare a String type reference variable that can point to a String object.
//It doesn't create an object.

String myString = new String();
//"new String()" is a constructor call. It creates a String object.
//assignment "=" causes myString to reference the String object.


Objects & Constructors
If an object is not referenced by a variable, it will eventually be deleted (garbage collection).
Constructors always have same name as their class, except "stuffinquotes".

3 ways to construct a string object:
1. new String()
2. "test"
3. new String("test")

Strings are immutable.

Some object reference examples:
e.g.
String s1 = new String();
s1 = "test";
String s2 = s1; //s1 and s2 reference to the same object
s2 = new String(s1); //s1 and s2 reference to different objects

e.g.
String s1; //null pointer (reference to nothing)
String s2 = s1; //s2 is also a null pointer
s1 = "test"; //while s2 still is a null pointer

e.g.
String s1;
String s2 = s1;
s1 = "test";
s2 = "test"; //Java will make s2 point to the same object that s1 pointed because their value is the same.
s2 = new String(s1); //force Java to create a copy of that String object.
s2 = s1;
s1 = "another test"; //now s2 = "test" while s1 = "another test"




No comments:

Post a Comment