Java Reference
In-Depth Information
53 System.out.print("What is today's price per share? ");
54 double currentPrice = console.nextDouble();
55
56
double profit = currentStock.getProfit(currentPrice);
57
System.out.println("Net profit/loss: $" + profit);
58
System.out.println();
59
return profit;
60 }
61 }
It would be useful to have a few other methods in our Stock objects. For example,
it would be good to implement accessors for the Stock 's data (the symbol, number of
shares, and so on), and a toString method to easily print Stock objects. We could
even add a second constructor that would accept an initial number of shares and cost.
These features are left for you to implement as exercises.
Chapter Summary
Object-oriented programming is a different philosophy of
writing programs that focuses on nouns or entities in a
program, rather than on verbs or actions of a program. In
object-oriented programming, state and behavior are
grouped into objects that communicate with each other.
To make objects easily printable, write a toString
method that returns the object's text representation.
A class can define special code called a constructor that
initializes the state of new objects as they are created. The
constructor will be called when external client code cre-
ates a new object of your type using the new keyword.
A class serves as the blueprint for a new type of object, speci-
fying the object's data and behavior. The class can be asked
to construct many objects (also called “instances”) of its type.
You can use the keyword this to have an object refer to
itself. It is also used when a class has multiple construc-
tors and one constructor wishes to call another.
Java's java.awt package has a class named Point . Each
object holds two int values, x and y . A Point can be
constructed, translated to a new location, and printed on
the console.
Objects can protect their internal data from unwanted
external modification by declaring them to be private ,
an action known as encapsulation. Encapsulation provides
abstraction so that clients can use the objects without
knowing about their internal implementation.
The data for each object are specified using special vari-
ables called fields.
The behavior of each object is specified by writing
instance methods in the class. Instance methods exist
inside an object and can access that object's internal state.
A class should represent only one key abstraction with
related data and behavior, and it should be independent
from its clients.
 
 
Search WWH ::




Custom Search