Você está na página 1de 6

COMPUTER PROGRAMMING-2 JAVA

CHAPTER-5
USER DEFINED CLASSES IN JAVA

DEFINING A CLASS IN JAVA

The general syntax for defining a class in Java is shown below.

class MyClassName{
...
} //End of class definition.

This syntax defines a class and creates a new type named MyClassName.

THE DEFINITIONS OF V ARIABLES AND METHODS ARE INSERTED BETWEEN


THE OPENING AND CLOS ING BRACES.
CREATING AND USING C LASSES AND OBJECTS

A class declaration names the class and encloses the class body between braces. The class
name can be preceded by modifiers. The class body contains fields, methods, and
constructors for the class. A class uses fields to contain state information and uses methods
to implement behavior. Constructors that initialize a new instance of a class use the name
of the class and look like methods without a return type.

You control access to classes and members in the same way: by using an access modifier
such as public in their declaration.

You specify a class variable or a class method by using the static keyword in the member's
declaration. A member that is not declared as static is implicitly an instance member. Class
variables are shared by all instances of a class and can be accessed through the class name
as well as an instance reference. Instances of a class get their own copy of each instance
variable, which must be accessed through an instance reference.

You create an object from a class by using the new operator and a constructor. The new
operator returns a reference to the object that was created. You can assign the reference to
a variable or use it directly.

Instance variables and methods that are accessible to code outside of the class that they are
declared in can be referred to by using a qualified name.

1 Mrs.Anamika Raj,Lecturer,KKU
COMPUTER PROGRAMMING-2 JAVA

The qualified name of an instance variable looks like this:

OBJECTREFERENCE.VARIABLENAME

The qualified name of a method looks like this:

OBJECTREFERENCE.METHODNAME(ARGUMENTLIST)

or:

OBJECTREFERENCE.METHODNAME()

The garbage collector automatically cleans up unused objects. An object is unused if the
program holds no more references to it. You can explicitly drop a reference by setting the
variable holding the reference to null.

Multiple classes in Java

USING MULTIPLE CLASS ES IN JAVA PROGRAM

Java program can contain more than one i.e. multiple classes. Following example Java
program contain two classes: Computer and Laptop. Both classes have their own
constructors and a method. In main method we create object of two classes and call their
methods.

USING TWO CLASSES IN JAVA PROGRAM

class Computer {
Computer() {
System.out.println("Constructor of Computer class.");
}

void computer_method() {
System.out.println("Power gone! Shut down your PC soon...");
}

public static void main(String[] args) {


Computer my = new Computer();
Laptop your = new Laptop();

my.computer_method();
your.laptop_method();
}

2 Mrs.Anamika Raj,Lecturer,KKU
COMPUTER PROGRAMMING-2 JAVA

class Laptop {
Laptop() {
System.out.println("Constructor of Laptop class.");
}

void laptop_method() {
System.out.println("99% Battery available.");
}
}

Output of program:

Passing Information to a Method or a Constructor

The declaration for a method or a constructor declares the number and the type of the
arguments for that method or constructor. For example, the following is a method that
computes the monthly payments for a home loan, based on the amount of the loan, the
interest rate, the length of the loan (the number of periods), and the future value of the
loan: public double computePayment(

double loanAmt,
double rate,
double futureValue,
int numPeriods) {
double interest = rate / 100.0;
double partial1 = Math.pow((1 + interest),
- numPeriods);
double denominator = (1 - partial1) / interest;
double answer = (-loanAmt / denominator)
- ((futureValue * partial1) / denominator);
return answer;}

3 Mrs.Anamika Raj,Lecturer,KKU
COMPUTER PROGRAMMING-2 JAVA

This method has four parameters: the loan amount, the interest rate, the future value and
the number of periods. The first three are double-precision floating point numbers, and the
fourth is an integer. The parameters are used in the method body and at runtime will take
on the values of the arguments that are passed in.

PROVIDING CONSTRUCTO RS FOR YOUR CLASSES

A class contains constructors that are invoked to create objects from the class blueprint.
Constructor declarations look like method declarationsexcept that they use the name of
the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {


gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument
constructor:

public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new
Bicycle object called yourBike.

Both constructors could have been declared in Bicycle because they have different
argument lists. As with methods, the Java platform differentiates constructors on the basis
of the number of arguments in the list and their types. You cannot write two constructors
that have the same number and type of arguments for the same class, because the platform
would not be able to tell them apart. Doing so causes a compile-time error.

4 Mrs.Anamika Raj,Lecturer,KKU
COMPUTER PROGRAMMING-2 JAVA

JAVA MODIFIERS

Modifiers are keywords that you add to those definitions to change their meanings. The
Java language has a wide variety of modifiers, including the following:
Java Access Modifiers
Non Access Modifiers

use a modifier, you include its keyword in the definition of a class, method, or variable. The

modifier precedes the rest of the statement, as in the following examples (Italic ones)

public class classNam e {

// ...

private boolean m yFlag;

static final double weeks = 9.5;

protected static final int BOXWIDTH = 42;

public static void m ain(String[] argum ents) {

// body of method

ACCESS CONTROL MODIF IERS:

Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:

Visible to the package, the default. No modifiers are needed.


Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).

5 Mrs.Anamika Raj,Lecturer,KKU
COMPUTER PROGRAMMING-2 JAVA

NON ACCESS MODIFIERS :

Java provides a number of non-access modifiers to achieve many other functionality.

The static modifier for creating class methods and variables


The final modifier for finalizing the implementations of classes, methods, and
variables.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.

6 Mrs.Anamika Raj,Lecturer,KKU

Você também pode gostar