Classes and Objects in Java
Classes and Objects in Java
com/)
• Data Fields - declare the data values belonging to the class or object
• Constructors - special functions called when an object is created to carry out initialization tasks.
• Methods - functions to carry out tasks for the objects.
• Member Classes - an inner class be defined within a class.
}
2. Variables in a method or block of code—these are called local variables.
3. Variables in method declarations—these are called parameters.
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified
and re-created. Any such misuse will be entertained by Indian Copyright Law.1
Technical Lobby, Raipur, Chhattisgarh, India (http://www.technicallobby.com/)
Class Variables –
When a number of objects are created from the same class blueprint, they each have their own distinct
copies of instance variables. In the case of the Bicycle class, the instance variables are cadence,
gear, and speed. Each Bicycle object has its own values for these variables, stored in different
memory locations.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the
static modifier. Fields that have the static modifier in their declaration are called static fields or
class variables. They are associated with the class, rather than with any object. Every instance of the
class shares a class variable, which is in one fixed location in memory. Any object can change the
value of a class variable, but class variables can also be manipulated without creating an instance of the
class.
5.5 Constants
The static modifier, in combination with the final modifier, is also used to define constants. The final
modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI , whose value is an
approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
After all the modifications made in this section, see the final bicycle class - BicycleFinal.java
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified
and re-created. Any such misuse will be entertained by Indian Copyright Law.2
Technical Lobby, Raipur, Chhattisgarh, India (http://www.technicallobby.com/)
1. Modifiers—such as public, private, and others you will learn about later.
2. The return type—the data type of the value returned by the method, or void if the
method does not return a value.
3. The method name—the rules for field names apply to method names as well, but the
convention is a little different.
4. The parameter list in parenthesis—a comma-delimited list of input parameters,
preceded by their data types, enclosed by parentheses, (). If there are no
parameters, you must use empty parentheses.
5. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here
instanceName.methodName(args)
but this is discouraged because it does not make it clear that they are class methods.
A common use for static methods is to access static fields. For example, we could add a static method
to the Bicycle class to access the numberOfBicycles static field:
• Instance methods can access instance variables and instance methods directly.
• Instance methods can access class variables and class methods directly.
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified
and re-created. Any such misuse will be entertained by Indian Copyright Law.3
Technical Lobby, Raipur, Chhattisgarh, India (http://www.technicallobby.com/)
• Class methods can access class variables and class methods directly.
• Class methods cannot access instance variables or instance methods directly—they must use an object
reference. Also, class methods cannot use the this keyword as there is no instance for this to refer
to.
The Java programming language supports overloading methods, and Java can distinguish between
methods with different method signatures. This means that methods within a class can have the same
name if they have different parameter lists.
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;
}
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified
and re-created. Any such misuse will be entertained by Indian Copyright Law.4
Technical Lobby, Raipur, Chhattisgarh, India (http://www.technicallobby.com/)
Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new
Bicycle object called yourBike.
Within an instance method or a constructor, this is a reference to the current object — the object whose
method or constructor is being called. You can refer to any member of the current object from within an
instance method or a constructor by using this.
The most common reason for using the this keyword is because a field is shadowed by a method or
constructor parameter.
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Each argument to the second constructor shadows one of the object's fields—inside the constructor x is a local
copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road
bikes, and tandem bikes, for example, all share the
characteristics of bicycles (current speed, current pedal
cadence, current gear). Yet each also defines additional features
that make them different: tandem bicycles have two seats
and two sets of handlebars; road bikes have drop
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified
and re-created. Any such misuse will be entertained by Indian Copyright Law.5
Technical Lobby, Raipur, Chhattisgarh, India (http://www.technicallobby.com/)
handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior from other
classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and
TandemBike. In the Java programming language, each class is allowed to have one direct superclass,
and each superclass has the potential for an unlimited number of subclasses.
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the
extends keyword, followed by the name of the class to inherit from:
class MountainBike extends Bicycle {
Access level modifiers determine whether other classes can use a particular field or invoke a particular
method. There are two levels of access control:
A class may be declared with the modifier public, in which case that class is visible to all classes
everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within
its own package.
At the member level, you can also use the public modifier or no modifier (package-private) just as with
top-level classes, and with the same meaning. For members, there are two additional access modifiers:
private and protected. The private modifier specifies that the member can only be accessed in its
own class. The protected modifier specifies that the member can only be accessed within its own
package (as with package-private) and, in addition, by a subclass of its class in another package.
The following table shows the access to members permitted by each modifier.
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified
and re-created. Any such misuse will be entertained by Indian Copyright Law.6
Technical Lobby, Raipur, Chhattisgarh, India (http://www.technicallobby.com/)
Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are
declared static are simply called static nested classes. Non-static nested classes are called inner classes.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to
other members of the enclosing class, even if they are declared private. Static nested classes do not have
access to other members of the enclosing class. As a member of the OuterClass, a nested class can be
declared private, public, protected, or package private. (Recall that outer classes can only be declared
public or package private.)
• It is a way of logically grouping classes that are only used in one place.
• It increases encapsulation.
• Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it
in that class and keep the two together. Nesting such "helper classes" makes their package more
streamlined.
More readable, maintainable code—Nesting small classes within top-level classes places the code
closer to where it is used.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like
any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in
another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object
within the outer object with this syntax:
This document is sole proprietary of Technical Lobby and any kind of misuse of this document is prohibited. This document should not be copied, modified
and re-created. Any such misuse will be entertained by Indian Copyright Law.9