JAVA Programing
Objects, Classes, Methods
What is Object Oriented Programming?
• Object oriented Programming languages (OOP for short) include all the features of structured programming and add still more powerful ways to organize algorithms and data structures. There are three key features of OOP languages:
– encapsulation
– inheritance
– polymorphism
All of them are tied to the notion of a class
Classes and Objects
The primary distinguishing feature of OOP languages is the class. A class is a set of variables (data members) that can be associated with the methods which act on an object with the object itself.
As the name object-oriented implies, objects are key to understanding object-oriented technology. You can look around you now and see many examples of real-world objects: your dog, your desk, your television set, your bicycle.
These real-world objects share two characteristics: they all have state and they all have behavior. For example, cars have state (current gear, number of seats, four wheels, etc.) and behavior (braking, accelerating, slowing down, changing gears).
Software objects are modeled after real-world objects in that they, too, have state and behavior. A software object maintains its state in variables and implements its behavior with methods.
Encapsulation
[pic]
As you can see from the above diagram, an object's variables make up the center or nucleus of the object. Methods surround and hide the object's nucleus from other objects in the program. This is called encapsulation.
Typically, encapsulation is used to hide unimportant implementation details from other objects. Thus, the implementation details can change at any time without affecting other parts of the program.
The Benefits of Encapsulation
• Encapsulation provides two primary benefits to software developers:
– Modularity -- the source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system.
– Information hiding -- an object has a public interface that other objects can use to communicate with it. But the object can maintain private information and methods that can be changed at any time without affecting the other objects that depend on it
What Are Classes?
A class is a blueprint or prototype that defines the variables and methods common to all objects of a certain kind.
In the real world, you often have many objects of the same kind. For example, your car is just one of many cars in the world. Using object-oriented terminology, we say that your car object is an instance of the class of objects known as cars. Cars have some state (current gear, number of seats, four wheels, etc.) and behavior (change gears, brake) in common. However, each car's state is independent of and can be different from other cars.
Defining a Class
A class definition takes the following form:
class MyClass {
// the members of the class go here
}
The class keyword is followed by the class name, which must be a valid Java identifier.
Example:
In our example we will have many thousands of Employees. Each specific employee is an object. The definition of a Employee though, which we gave above, is a class.
This is a very important distinction. A class defines what an object is, but it is not itself an object. An object is a specific instance of a class.
Thus when we create a new object we say we are instantiating the object. Each class exists only once in a program, but there can be many thousands of objects that are instances of that class.
To instantiate an object in Java we use the new operator. Here's how we'd create a new employee:
Employee x = new Employee();
The members of an object are accessed using the . (dot) operator, as follows:
Note when you compile the file Employee.java, you get two class files:
Employee.class and TestEmployee.class.
A member declared as public in a class is accessible to all other methods.
A member declared as private in a class is accessible only to other members of the same class.
A member which is not marked is said to be friendly and can directly accessible to other members of the same package. In particular, friendly accessible to all classes within the same java source file.
Overloading Methods
Two methods can have the same name as long as they have different argument lists. This is called method overloading.
Example
Static Members (Class Members)
Most properties, like the balance in bank account, are unique to the object. But some properties are shared among all objects of a given class. For example, the interest rate is a property shared by all saving accounts in the same bank.
Such properties are called class member.
Class members are defined using the keyword static. So class members are also called static members (e.g. Math class).
Static Methods
Methods can also be declared static.
A static method does not associate with any objects so that it cannot access nonstatic class members.
Java allows programmer to call a static method using the name of the class rather than an object name.
Example: The static method you are already very familiar with is
public static void main(String[] args)
Advantage of static methods: you don't have to create an object before using a static method.
You can still call a static method using an object rather than a class name.
Final Members
It is possible to define a data member as final, meaning that its value is not changeable.
A final variable must be initialised. (JDK1.1 introduced "blank final variable" which is simply a final variable that doesn't have an initializer. A blank final variable must be assigned an inital value, and that can be assigned only once.)
Example:
Object References
Java has no explicit pointers. Instead, Java offers references.
You might have noticed that a class object is not created the same way an intrinsic variable is created:
int i; // intrinsic variable
Employee emp = new Employee(); // class object
The declaration Employee emp declares not an Employee object but a reference to an Employee object.
Java will set any uninitialised reference to null. Any attempt to use a null reference generates an exception.
You can assign any reference to refer to a real object:
Employee emp; // emp references the null object
emp = new Employee(); // now emp references a real Employee object
It is legal for two references to refer to the same object:
Employee emp = new Employee();
Employee mgr = emp; // mgr refers to the same Employee as emp
So What is a Reference?
You can think of a reference as a name for an object.
I have a dog. The dog is an object. I can name it Lucky. Lucky is a reference to the dog. I can give my dog several names: Lucky, Fido, Stupid. Each of these references refers to the same dog (object).
A reference can be redirected. For example, I got another new dog and name it Lucky. When I say Lucky, I am referring to my new dog. This is similar to assigning a reference to point to a different object.
Passing References to Functions
As all variables except intrinsic objects are references, a class object passed as an argument to a function remains modified in the calling function (call by reference).
However, an intrinsic object does not remain modified when passed as an argument to a function (call by value).
Cleaning Up Lost Objects: Garbage Collection
Object can get lost. Consider the following code segment:
public static void SomeFunc() {
//allocate an object
Employee emp = new Employee();
// ... does something and then exits
}
Here the reference emp is local to the function SomeFunc. When the function exits, emp goes out of scope and the object is no longer accessible. Java is free to reclaim its memory and put it back into the heap.
Java does the memory recovery in a process known as garage collection.
Java performs garbage collection under the following circumstances:
– Whenever it needs to. When the amount of memory is not enough
– Whenever you ask. You can force garbage collection by calling System.gc.
– Whenever it gets around to it. Java continually runs a low priority background
task that looks for things to throw away.
Constructor
A constructor is a special method with the same name as the class that is invoked automatically whenever a class object is created.
A constructor initialises all the variables and does any work necessary to prepare the class to be used.
A constructor has no return type, not even void.
If no constructor is defined by the programmer, a default "do-nothing" constructor is created for you.
• Java does not provide a default constructor if the class define a constructor of its own.
What about Static Data?
To initialise static data members, Java defines a special constructor for static members, called static initialiser.
Explicit Use of this pointer
• Sometimes it is necessary to use the this pointer explicitly within the member function. A typical example of this is to distinguish a local variable and data member which have the same name.
• You will find out more useof this pointer in the laboratory session.
toString
• All classes in Java are extending the class Object.
• One method in the Object class is toString which which will return a string that "textually represents" the object.
• You can override the toString method to produce more meaningful message.
Additional Java features
• The break statement can also be labelled to allow control to pass out of multiple loops at one time by using break label.
• The statement break outHere does not pass control to the label. Rather, it passes control outside of the loop labelled outHere.
Example - Labelled Break
Using the Standard I/O Objects
Java provides three static standard objects for I/O:
Object Type
System.in BufferedInputStream
System.out PrintStream
System.err PrintStream
Java views the input data as a sequential stream of bytes and System.in has a lower level method read() to read a number of bytes from the standard input.
Reading String
We can use the function System.out.write to print the byte array read. Let us begin by writing a very simple program that asks the user for their name and then prints a personalized greeting.
Remark : Don't run this example using FreeJava, use command line instead.
The block
try {
......
}
catch (......) {
......
}
is used to handle the exception generated by the run-time system. Some exceptions can ignored but the IOException must be caught. So the main method must have a try-catch block to handle any exception generated.
Reading Numbers
The object InputStream doesn't offer anything more sophisticated than read(bytes[]). So we have to convert the array of bytes to the type we need. This involves some works to convert the byte array to a String object and then parse it to the desired types.
Another method is to use DataInputStream which is used to read formatted data.
Reading Formatted Data
If you enter any non-digit as the input to the above program, you will get a run-time syntax error. It is because the method Integer.valueOf accept signed numbers only.
To read text and numbers on the same line, you need to use the StreamTokenizer class.
Command Line Arguments
• You can pass command line arguments to your program.
java Hello May Tom Sue
• Compile the following program usual and run it with some command line arguments.
-----------------------
Class
Object3
Object2
Object1
class Employee {
int empnum; // data member
public int Num() { // method
return empnum;
}
public void setNum(int newNum) { // method
empnum = newNum;
}
}
// Employee.java
class Employee {
int empnum; // data member
public int Num() { // method
return empnum;
}
public void setNum(int newNum) { // method
empnum = newNum;
}
}
class TestEmployee {
public static void main(String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee();
emp1.setNum(12651);
emp2.setNum(36595);
System.out.println("num of emp1 : " + emp1.Num());
System.out.println("num of emp2 : " + emp2.Num());
}
}
Sample Run
$ java TestEmployee
num of emp1 : 12651
num of emp2 : 36595
// TestOverload.java
class Employee {
int empnum; // data member
public int Num() { // get method
return empnum;
}
public void Num(int newNum) { // set method
empnum = newNum;
}
}
class TestOverload {
public static void main(String[] args) {
Employee emp = new Employee();
emp.Num(98165);
System.out.println("num of emp : " + emp.Num());
}
}
Sample Run
$ java TestOverload
num of emp : 98165
// TestStatic.java
class Employee {
static int MaxNum; // data member
int empnum; // data member
public int Num() { // method
return empnum;
}
public void setNum(int newNum) { // method
if (newNum1)
empnum = newNum;
}
}
class TestStatic {
public static void main(String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee();
emp1.MaxNum = 99999;
System.out.println("MaxNum of emp2 : " + emp2.MaxNum);
}
}
Class (Static) Members
MaxNum
Object3
Object2
Object1
(nonstatic members)
empnum
Sample Run
$ java TestStatic
MaxNum of emp2 : 99999
// TestStaticMethod.java
class Employee {
static int MaxNum; // data member
int empnum; // data member
public static void setMaxNum(int newMaxNum) {
MaxNum = newMaxNum;
}
}
class TestStaticMethod {
public static void main(String[] args) {
Employee.setMaxNum(88888);
System.out.println("MaxNum of Employee : " + Employee.MaxNum);
Employee emp = new Employee();
emp.setMaxNum(99999);
System.out.println("MaxNum of emp : " + emp.MaxNum);
}
}
Sample Run
$ java TestStaticMethod
MaxNum of Employee : 88888
MaxNum of emp : 99999
class Employee {
final static int MaxNum = 99999; // not modifiable
//.... so on like before
}
Call by Reference
all other objects
Call by Value
boolean
byte
short
int
long
float
double
char
// PassRef.java
class Employee {
int empnum; // data member
}
class PassRef {
public static void main(String[] args) {
Employee emp = new Employee();
emp.empnum = 81619;
System.out.println("num of emp : " + emp.empnum);
ModifyEmpNum(emp); // call by reference
System.out.println("num of emp : " + emp.empnum);
}
private static void ModifyEmpNum(Employee Emp) {
Emp.empnum = 71621;
}
}
Sample Run
$ java PassRef
num of emp : 81619
num of emp : 71621
// TestConstructor.java
class Employee {
int empnum; // data member
public Employee() { // constructor
empnum = 99999;
}
public Employee(int newNum) { // constructor
empnum = newNum;
}
}
class TestConstructor {
public static void main(String[] args) {
Employee emp1 = new Employee();
System.out.println("num of emp1 : " + emp1.empnum);
Employee emp2 = new Employee(81263);
System.out.println("num of emp2 : " + emp2.empnum);
}
}
Sample Run
num of emp1 : 99999
num of emp2 : 81263
// TestStaticInit.java
class Employee {
static int MaxNum; // static data member
static { // static initialiser
MaxNum = 988;
}
}
class TestStaticInit {
public static void main(String[] args) {
System.out.println("MaxNum of Employee : " + Employee.MaxNum);
}
}
Sample Run
num of emp1 : 99999
num of emp2 : 81263
Sample Run
$ java TestStaticInit
MaxNum of Employee : 988
Sample Run
num of emp1 : 99999
num of emp2 : 81263
Sample Run
num of emp1 : 99999
num of emp2 : 81263
Sample Output
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
Program exits.
// LabeledBreak.java
class LabeledBreak {
public static void main (String args[]) {
int i = 0;
outHere:
while (ijava Hello
Hello whoever you are
command line arguments
program name
// Hello.java
class Hello{
public static void main (String args[]) {
System.out.print("Hello ");
if (args.length == 0)
System.out.println("whoever you are");
else {
for (int i=0; i ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- java sample code for beginners
- java this example
- this in java code
- all java codes
- sample java code
- java minecraft free download windows 10
- minecraft free download full version java edition
- minecraft java edition free download
- minecraft java edition full version
- basic java programming examples
- java collections tutorial with examples
- java sample programs