0% found this document useful (0 votes)
27 views23 pages

Java Module 2

- Classes are the fundamental building blocks of Java programs and everything must be encapsulated within a class. Classes create objects which communicate via methods. - There are three types of variables in a class: instance variables, class/static variables, and constants. Instance variables are declared within a class but outside methods while class variables use the static keyword. - Objects are created using the new operator and access class members like variables and methods using dot notation. Methods are defined with a return type, name, parameters, and body. The this keyword refers to the current object.

Uploaded by

AKSHAY K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
27 views23 pages

Java Module 2

- Classes are the fundamental building blocks of Java programs and everything must be encapsulated within a class. Classes create objects which communicate via methods. - There are three types of variables in a class: instance variables, class/static variables, and constants. Instance variables are declared within a class but outside methods while class variables use the static keyword. - Objects are created using the new operator and access class members like variables and methods using dot notation. Methods are defined with a return type, name, parameters, and body. The this keyword refers to the current object.

Uploaded by

AKSHAY K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

JAVA CLASSES

● Classes are the fundamental building blocks of any object-oriented language.


● Java is a true object-oriented language and therefore the underlying structure of all Java
programs is classes.
● Anything we wish to represent in a Java program must be encapsulated in a class.
● Classes create objects and objects use methods to communicate between them.
● Classes provide a convenient method for packing together a group of logically related data items
and functions that work on them.
● In java the data items are called fields and the functions are called methods.

● A class can be defined as follows:

class Rectangle

Body of the class

● Every class defined in Java is a child of the Object class.

Creating Instance and class variables

● A class usually contains variables and methods.


● Certain specific rules have to be followed for defining variables and methods within a class.
● A variable is an identifier that denotes a storage location used to store a data value.

● Different types of variables are

1. Instance variable:

● Instance variables are declared and defined in almost the same way as local variables.
● the main difference being their location in the class definition.
● Variables are considered instance variables if they are declared outside a method definition.
● It is customary to define instance variables just after the first line of the class definition.

2. Constants:

● A constant variable or constant is a variable whose value never changes.

● Constants are used to define shared values for all the methods of an object.
● In Java, only instance and class variables can be constants (not local variables).
● To declare a constant, the keyword final is used .
● It should be placed before declaration of the variable and should include an initial value for that
variable, as shown in the following examples:

final float pi= 3.14;

final boolean debug = false;


final int maxsize = 40000;

● Constants can be useful for naming various states of an object and testing them.

​3.Class variables:

● Class variables are global to a class and to all instances of that class.
● Class variables are used for communication between different objects within the same class.
● The static keyword is used in the class declaration to declare a class variable.
● Some examples of this are given below:

static int sum

static final int maxObjects = 10;

CREATING OBJECTS

● An object in Java is essentially a block of memory that contains space to store all the instance
variables.
● Creating an object is also referred to as instantiating an object.
● Objects in Java are created using the new operator.

Example:

Rectangle rect;
rect=new Rectangle();
OR

Rectangle rect=new Rectangle();

ACCESSING CLASS MEMBERS

objectname.variablename=value;

objectname .methodname(parameter-list);

● Here objectname is the name of the object,


● variablename is the name of the instance variable inside the object that we wish to access,
● methodname is the method that we wish to call,
● and parameter- list is a comma separated list of actual values that must match in type and
number with the parameter list of the method name declared in the class.

Eg:

rect.length=10;

rect.width=5;

Eg:

rect.area(10,5);
Defining methods

In Java, method definition usually consists of four fundamental parts,

● the name of the method,


● the object type or the data type that the method returns (referred to as return type),
● the list of parameters and
● the body of the method.
The first three constituents of the method definition are referred to as method declaration
or method signature. The method declaration usually gives the important information about the method
itself.

In other programming languages, method names (function, subroutine or procedure numes) are
unique; however, in Java, different methods can have the same name, but a different return type or
argument list.

The process of having methods with the same name but with different retum type is referred to as
method overloading.

In Java, a method is defined as follows:

returntype methodname (type1 arg1,

type2 arg2, type 3 ang3….)

body of the method

Knowing this

● Programmers sometimes refer to the current object (that is, the object in which the method is
contained in the first place) within the body of a method.
● Java provides the keyword this to refer to the current object.
● The keyword this can be used anywhere the current object might appear.
● It can be used in dot notation to refer to the object's instance variables, as an argument to a
method, as the return value for the current method and so on.
● This is illustrated in the following examples:

t = this.x; //the x instance variable for this object

this.myMethod(this); // calls the myMethod

method, defined in this class and passes

it to the current object.

return this; // returns the current object.

Variable Scope

● The scope of a variable specifies the region of the source program where that variable is known,
accessible and can be used.
● In Java, the declared variable has a definite scope.
● When a variable is defined within a class, its scope determines whether it can be used only within
the defined class or outside of the class also.
● Local variables can be used only within the block in which they are defined.
● The scope of instance variables covers the entire class, so they can be used by any of the
methods within that class.
● Variables must be declared before usage within a scope.
● Variables that are declared in an outer scope can also be used in an inner scope.

Passing arguments to methods

There are mainly two ways of passing arguments to methods:

● Pass by value .
● Pass by reference

​Java directly supports passing by value; however, passing by reference will be accessible
through reference objects.

1 . Pass by value

● When the arguments are passed using the pass by value mechanism, only a copy of the
variables are passed which has the scope within the method which receives the copy of these
variables.
● The changes made to the parameters inside the methods are not returned to the calling method.
● This ensures that the value of the variables in the calling method will remain unchanged after
return from the calling method.

2.Pass by reference

● In the pass by reference mechanism, when parameters are passed to the methods, the calling
method returns the changed value of the variables to the called method.
● The call by reference mechanism is not used by Java for passing parameters to the methods.
Rather it manipulates objects by reference and hence all object variables are referenced.

Method Overloading

● It is possible to create methods that have the same name, but different parameter lists and
different definitions. This is called method overloading.
● The process of having methods with the same name but with different return type is referred to as
method overloading.
● In the above class, two methods are defined with the same name, that is, First().
● The first method does not contain any arguments but displays a string when called.
● The second method has two integers in its parameter list. Invoking this method gives the sum of
the two integers.
● When First() is invoked from the main method it displays the text, and when First(10,20) is
invoked, it adds up the two numbers and gives 30 as output.

CONSTRUCTOR METHODS

When an object is created in Java using the keyword new the following things happen:

● Memory is allocated for the new object


● Instance variables of the object are initialized.
● A constructor method is invoked.

Basic Constructor

Constructors look like methods ,with two basic differences:


● Constructors always have the same name as the class.
● Constructors do not have a return type.
​Subclass Constructor

● A subclass constructor is used to construct the instance variables of both the subclass and the
superclass.
● The subclass constructor uses the keyword ​super​ to invoke the constructor method of the
superclass.

The keyword super is used subject to the following conditions.

● Super may only be used within a subclass constructor method.


● The call to superclass constructor must appear as the first statement within the subclass
constructor.
● The parameters in the super call must match the order and type of the instance variable declared
in the super class.

Overloading Constructors

Similar to methods, constructors can take many different numbers and types of parameters in the
body of one program, enabling the programmer to create objects with desired functionality.Following
Program shows the example of a class Room that has overloaded constructors.
INHERITANCE : EXTENDING A CLASS

● The mechanism of deriving a new class from an old one is called inheritance.
● The old class is known as the base class or super class or parent class and the new one is called
the subclass or derived class or child class.
● Inheritance may take different forms:
● Single inheritance( only one super class)
● Multiple inheritance(several super classes)
● Hierarchical inheritance(one super class,many subclasses)
● Multilevel inheritance( derived from a derived class)

Java does not directly implement multiple inheritance.In Java, multiple inheritance is
implemented by using Interfaces.

DEFINING A SUBCLASS

A subclass is defined as follows:

● The keyword extends signifies that the properties of the superclassname are extended to the
subclassname.
● The subclass will now contain its own variables and methods as well as those of the superclass.
● This kind of situation occurs when we want to add some more properties to an existing class
without actually modifying it.
Multilevel Inheritance

● The chain ABC is known as inheritance path.


● A derived class with multilevel .The class A serves as a base class for the derived class B which
in turn serves as a base class for the derived class C.
● base classes is declared as follows:
● This process may be extended to any number of levels.
● The class C can inherit the members of both A and B.

Hierarchical Inheritance

● Many programming problems can be cast in to a hierarchy where certain features of one level are
shared by many others below the level.
OVERRIDING METHODS

● This is possible by defining a method in the subclass that has the same name, same arguments
and same return type as a method in the superclass
● When that method is called,the method defined in the subclass is invoked and executed instead
of the one in the superclass.
● This is known as ​overriding.
● In the below pgm,the method display() is overriden.

MODIFIERS

● Modifiers are keywords used to define the scope and behaviour of classes, methods and
variables in Java.
● Java has a wide variety of modifiers:

1. Modifiers for controlling access to a class, method or variable, which are:


● public
● protected ​and
● private
These are also termed access modifiers.

2. The ​static ​modifier for creating class


methods and variables.

3. The ​abstract​ modifier,for creating abstract


classes and methods.

4. The ​final ​modifier, for finalizing the


implementations of classes,methods and
variables.

5. The ​synchronized ​and ​volatile ​modifiers, which


are used for threads.

6. The ​native ​modifier,which is used for


creating native methods.

Controlling access to methods and variables

● While a class may define various methods and variables, not all of them are useful, and some
may even be harmful, if they are not used in the way they are intended to be used.
● Access control is about controlling visibility.

Why access control is important?

● When a method or variable is visible to another class, methods of the second class can reference
(that is, call or modify) that method or variable .
● Protecting those methods and instance variables limits the visibility and the use of those methods
and variables.
● As a designer of a class or an entire hierarchy of classes, it is a good idea to define what the
external appearance of a class is going to be, which variables and methods will be accessible for
other users of that class, and which ones are for internal use only. This is called encapsulation
and is an important feature of object oriented design.

Encapsulation is the process of hiding the internal parts of an object implementation and allowing
access to that object only through a defined interface.

The four Ps of protection

Java provides four levels of protection for methods and instance variables:
● public,
● private,
● protected and
● package

Package​ :

● Methods and variables with package protection are visible to all other classes in the same
package but not outside that package.
● Most of the time, the programmer needs to be more explicit when protection is defined for
methods and variables of a class.
● Package protection is the default level of protection Package protection is not an explicit modifier,
it can be added to the definition of a method or variable.

Private

● The keyword private limits the visibility of methods and instance variables to the class in which
they are defined.
● For example, private instance variables can be used by methods inside the same class but
cannot be seen or used by any other class or object.
● In addition, neither private variables nor private methods are inherited by subclasses.
● Private protection ensures that methods and variables are accessible only to other methods in the
same class.

Public

● The opposite of private, and the least restrictive form of protection, is public.
● A method or variable that is declared with the modifier public is accessible to the class in which it
is defined and all the sub-classes of that class, as well as all the classes in the package and any
other classes outside that package.

Protected

● The final form of protection available in Java concerns the relationship between a class and its
present and future sub-classes declared inside or outside a package.
● These sub classes are much closer to a particular class than to any other 'outside' classes.
● To support a special level of visibility reserved for sub-classes that are required to be somewhat
less restricted than private, Java offers an intermediate level of access between package and
private calls, protected.
● The keyword protected implies that those methods and variables are accessible to all classes
inside the package and only sub-classes outside the package.
Finalizer methods

● Finalizer methods are almost the opposite of constructor methods.


● A constructor method is used to initialize an object, while finalizer methods are called just before
the object is garbage-collected and its memory reclaimed.
● The syntax of the finalizer method is simply finalize().

Abstract classes and methods

● A class with minimal functionality is known as an abstract class.


● Usually the sub-class of an abstract class contains the functionality.
● To define a class as abstract, the keyword abstract is used.
● The syntax for using abstract is as follows:

public abstract class ExampleAbstractClass


{
… . ..
}

Abstract classes can never be instantiated, but they can contain class and instance variables and
methods.

● In addition, abstract classes can also contain abstract methods.


● An abstract method is a method signature with no implementation, and sub-classes of the
abstract class are expected to provide the implementation for that method.
● Abstract methods function in the same manner as abstract classes:they are a way of factoring
common behaviour into super-classes and then providing specific concrete uses of those
behaviours in sub-classes.
● Abstract methods can only exist inside abstract classes. This is because abstract methods cannot
be called and they have no implementation.

● Abstract classes are classes whose sole purpose is to provide common information for
sub-classes. Abstract classes can have no instances.
● Abstract methods are methods with signatures, but no implementation. The sub-classes of
the class that contains that abstract method must provide its actual implementation.

PACKAGES

● Packages are Java's way of grouping a variety of classes and/or interfaces together.
● A package in Java is a group of related classes, interfaces and sub-packages.

Advantages of using Packages

● They help in organizing classes into units. Just as a computer hard disk contains folders or
directories to organize files and applications ,packages allow organization of classes into groups.
● They reduce problems with conflicts in names.
● Package provide protection to variables, methods and classes in finer way.
● Package can be used to identify classes.
● Packages provide a way to hide classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.

Java packages are classified into two types.


1. Java API package.
2. User defined package.

JAVA API PACKAGES

USING PACKAGES
● In order to access a package within a particular program the keyword ​import ​followed by the
package name is used.
● All the class, variables and methods within a package can be imported.
● The ​import ​keyword ensures that the desired package with its contents is available to the
program in which it is invoked.
● Using ​import​,the entire package or individual class can be imported.
● The syntax is:
import packagename. classname;
import packagename.*;
E.g:
import java .util. Vector;
import java .util.*;

● When the asterisk (*) is used , It implies that all the public classes ,methods and variables can be
accessed by the class in a program in which the package is imported.

CREATING PACKAGES (USER DEFINED PACKAGES)

● Java allows programmers to create their own packages.


● Package creation is quite easy.
● Steps for creating packages are:

1. Declare the package at the beginning of a file using the form:


​ ackage packagename;
p
2. Define the class that is to be put in the
package and declare it public.
3. Create the sub directory under the directory
where the main source files are stored.
4. Store the listing as the classname. java file
in the sub directory created.
5. Compile the file. This creates .class file in
the subdirectory.

INTERFACES: MULTIPLE INHERITANCE


● Java does'nt support multiple inheritance
● That is, classes in Java can't have more than one superclass.
● For instance, a definition like

is not permitted in Java .


● Java provides an alternate approach known as interfaces to support the concept of multiple
inheritance.

DEFINING INTERFACES

● An interface is basically a kind of class.


● Like classes ,interfaces contain methods and variables but with a major difference.
● The difference is that interface define only abstract methods and final fields.
● This means that interface do not specify any code to implement these methods and data fields
contain only constants.
● Therefore, it is the responsibility of the class that implements an interface to define the code for
implementation of these methods.
● The syntax for defining an interface is very similar to that for defining a class. The general form of
an interface definition is:

● Here interface is the keyword and InterfaceName is any valid Java identifier just like class names.
● Variables are declared as follows:
static final type VariableName=Value;
● All variables are declared as constants.
● Method declaration will contain only a list of methods without any body statements.

Eg:
return_type methodName(parameter_list);

EXTENDING INTERFACES

● Like classes, interfaces can also be extended.


● That is, an interface can be subinterfaced from other interfaces.
● This is achieved using the keyword ​extends.

Eg:

IMPLEMENTING INTERFACES

● Interfaces are used as "superclasses" whose properties are inherited by classes.


● It is therefore necessary to create a class that inherits the given interface.
● This is done as follows:
● Here the classname "​implements​" the interface interfacename.

● A more general form of implementation may look like this:

● This shows that a class can extend another class while implementing interfaces.
● When a class implements more than one interface, they are separated by a comma.
● The implementation of interfaces can take various forms as :

Program: implementing interface


DIFFERENCE BETWEEN CLASS AND INTERFACE

You might also like