0% found this document useful (0 votes)
19 views

Java Introduction

The document discusses programming languages and Java, describing Java as an object-oriented language influenced by C and C++ that allows for the creation of simple, secure, portable and robust applications through features like abstraction, encapsulation, inheritance and polymorphism. It also outlines the process of creating, compiling and executing Java programs and discusses naming conventions, comments, keywords and data types in Java.

Uploaded by

lencho03406
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java Introduction

The document discusses programming languages and Java, describing Java as an object-oriented language influenced by C and C++ that allows for the creation of simple, secure, portable and robust applications through features like abstraction, encapsulation, inheritance and polymorphism. It also outlines the process of creating, compiling and executing Java programs and discusses naming conventions, comments, keywords and data types in Java.

Uploaded by

lencho03406
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Introduction

Programming Language
• It is different category of written symbols that instruct computer
hardware to perform specified operations required by the designer.
• Skills required to be a programmer:
• Programming Language Skill: knowing one or more programming
language to talk to the computer and instruct the machine to
perform a task.
• Problem Solving Skill: skills on how to solve real world problem
and represent the solution in understandable format.
• Algorithm Development: skill of coming up with sequence of
simple and human understandable set of instructions showing the
step of solving the problem. Those set of steps should not be
dependent on any programming language or machine.
1
Java language
• Java is related to C++, which is a direct descendant of C.
• Much of the character of Java is inherited from C and C+
+.
• From C, Java derives its syntax. Many of Java’s object-
oriented features were influenced by C++.
• In fact, several of Java’s defining characteristics come
from—or are responses to—its predecessors.
• the creation of Java was deeply rooted in the process of
refinement and adaptation that has been occurring in
computer programming languages for the past several
decades
2
Features of Java
• Simple: Learning and practicing java is easy because of resemblance
with c and C++.

• Object Oriented Programming Language: Unlike C++, Java is


purely OOP.

• Distributed: Java is designed for use on network; it has an extensive


library which works in agreement with TCP/IP.

• Secure: Java is designed for use on Internet. Java enables the


construction of virus-free, tamper free systems.
3
Features of Java…
• Architecture-Neutral: the goal of java developers was “write
once; run anywhere, any time, forever.
• Upgrade of processor, upgrade of operating system or changes
in core system resources does not affect java program.
• Dynamic
• Java programs carry with them substantial amounts of run-time
type information that is
• used to verify and resolve accesses to objects at run time. This
makes it possible to dynamically link code in a safe and
expedient manner

4
Features of Java…
• Robust (Strong/ Powerful): Java programs will not crash because of
its exception handling and its memory management features.

• Interpreted: Java programs are compiled to generate the byte code.


This byte code can be downloaded and interpreted by the
interpreter. .class file will have byte code instructions and JVM which
contains an interpreter will execute the byte code.

• Portable: Java does not have implementation dependent aspects and it


yields or gives same result on any machine.
5
OOP Principles

• All object-oriented programming languages provide


mechanisms that help you implement the object-oriented model.

• They are:
 abstraction
encapsulation,
inheritance, and
polymorphism. 6
Abstraction

• An essential element of object-oriented programming is abstraction.


• Abstraction is a powerful methodology to manage complex systems.
• For example, people do not think of a car as a set of tens of thousands
of individual parts.
• people think of it as a well-defined object with its own unique behavior.
• This abstraction allows people to drive car without being overwhelmed by
the complexity of the parts that form the car
• A powerful way to manage abstraction is through the use of
hierarchical classifications.
• This allows you to layer the semantics of complex systems, breaking
them into more manageable pieces.

7
Encapsulation

• Encapsulation is the mechanism that binds together code


and the data it manipulates, and keeps both data and code
safe from outside interference and misuse.
• One way to think about encapsulation is as a protective
wrapper that prevents the code and data from being
arbitrarily accessed by other code defined outside the
wrapper.
• Access to the code and data inside the wrapper is tightly
controlled through a well-defined interface

8
Inheritance

• Inheritance is the process by which one object acquires the properties of


another object.

• This is important because it supports the concept of hierarchical classification.

• Without the use of hierarchies, each object would need to define all of its
characteristics explicitly.

• However, by use of inheritance, an object need only define those qualities that
make it unique within its class. It can inherit its general attributes from its
parent.
9
Polymorphism
• Polymorphism meaning many forms is a feature that allows one
interface to be used for a general class of actions.

• The specific action is determined by the exact nature of the situation.

• the concept of polymorphism is often expressed by the phrase one


interface, multiple methods.

• This means that it is possible to design a generic interface to a group of


related activities.

• This helps reduce complexity by allowing the same interface to be used


to specify a general class of action. 10
Java Editions

• Java is a full-fledged and powerful language that can be used in many


ways.
• It comes in three editions:
• Java Standard Edition (Java SE),
• Java Enterprise Edition (Java EE), and
• Java Micro Edition (Java ME).
• Java SE can be used to develop client-side standalone applications or
applets.
• Java EE can be used to develop server-side applications, such as Java
servlets and JavaServer Pages.
• Java ME can be used to develop applications for mobile devices, such
as cell phones.
11
Creating, Compiling, and Executing a Java Program
• You have to create your program and compile it before it can be
executed. This process is repetitive.

• If your program has compilation errors, you have to modify the


program to fix them, then recompile it.

• If your program has runtime errors or does not produce the


correct result, you have to modify the program, recompile it, and
execute it again

12
Executing a Java Program…

13
Java editors

• To write Java programs, a text editor will be needed.


• Notepad,
• net beans,
• eclipse, and
• IntelliJ

14
Naming Conventions

• Naming conventions specify the rules to be followed by a Java programmer


while writing the names of packages, classes, methods etc.
• Package names are written in small letters.
• e.g.: java.io, java.lang, java.awt etc
• Each word of class name and interface name starts with a capital
• e.g.: Sample, AddTwoNumbers
• e.g.: suMethod names start with small letters then each word start with a capital
• m (), sumTwoNumbers (), minValue ()
• Variable names also follow the same above method rule
• e.g.: sum, count, totalCount
• Constants should be written using all capital letters
• e.g.: PI, COUNT
• Keywords are reserved words and are written in small letters.
• e.g.: int, short, float, public, void
15
Java comments

• Comments are remarks added into a program’s source file.

• The contents of a comment are ignored by the compiler. Instead, a comment


describes or explains the operation of the program to anyone who is reading its
source code.

• Java supports three styles of comments.


• // single line comment
• /* multiline comment*/
• /** The documentation comment */.
16
The Java Keywords

• There are 50 keywords currently defined in the Java language.

• These keywords, combined with the syntax of the operators and separators, form
the foundation of the Java language.

• These keywords cannot be used as identifiers. Thus, they cannot be used as


names for a variable, class, or method.

• The keywords const and goto are reserved but not used.

• In addition to the keywords, Java reserves the following: true, false, and null.
These are values defined by Java. You are not allowed to use these words for the
names of variables, classes, and so on.
17
The Java Keywords…

18
Data types

• Java is a strongly typed language, which means every


variable has a type, every expression has a type, and every
type is strictly defined.

• And also, all assignments, whether explicit or via parameter


passing in method calls, are checked for type compatibility.

• The Java compiler checks all expressions and parameters to


ensure that the types are compatible.
19
The Primitive Types

Java defines eight primitive types of data: byte, short, int, long, char,
float, double, and boolean. The primitive types are also commonly
referred to as simple types.
These can be put in four groups:
• Integers: This group includes byte, short, int, and long, which are for whole-
valued signed numbers.
• Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
• Characters: This group includes char, which represents symbols in a character
set, like letters and numbers.
• Boolean:This group includes boolean, which is a special type for representing
true/false values.
20
Integer Data type

• Java defines four integer types: byte, short, int, and long. All of these
are signed, positive and negative values.

21
Variables

• The variable is the basic unit of storage in a Java program.


• It is defined by the combination of an identifier, a type, and an optional
initializer. In addition, all variables have a scope, which defines their
visibility, and a lifetime.
Variable declaration
• In Java, all variables must be declared before they can be used. The
basic form of a variable declaration is follows:
• type identifier = value , identifier = value…;
• Here, type is one of Java’s atomic types, or the name of a class or
interface.
• The identifier is the name of the variable. You can initialize the variable
by specifying an equal sign and a value.
22
Variables…
int a, b, c;// declares three ints, a, b, and c.
int d = 3, e, f = 5;// declares three more ints, initializing d and
f.
byte z = 22;// initializes z.
double pi = 3.14159;// declares an approximation of pi.
char x = 'x';// the variable x has the value 'x'.

23
Arithmetic Operators

24
Increment and Decrement

• The increment operator increases its operand by one. The


decrement operator decreases its operand by one.

• For example, this statement: x = x + 1;

• Can be rewritten like this by use of the increment operator:


x++;

• Similarly, this statement: x = x - 1; is equivalent to: x--;

25
Increment and Decrement…
• These operators are unique in that they can appear both in postfix
form, where they follow the operand, and prefix form, where they
precede the operand.

• In the prefix form, the operand is incremented or decremented before


the value is obtained for use in the expression.

• In postfix form, the previous value is obtained for use in the


expression, and then the operand is modified.
• For example: x = 12; y = ++x;
26
Increment and Decrement…

• Thus, the line y = ++x; is the equivalent of these two statements:


• x = x + 1; y = x;
• However, when written like this, x = 12; y = x++;
• The value of x is obtained before the increment operator is
executed, so the value of y is 12.
• Of course, in both cases x is set to 13. Here, the line y = x++; is
the equivalent of these two statements:
• y = x; x = x + 1;
27
Relational Operators

• The relational operators determine the relationship that one operand


has to the other.
• Specifically, they determine equality and ordering.

28
Assignment Operator

• The assignment operator is the single equal sign, =.

• The assignment operator works in Java much as it does in


any other computer language.

• It has this general form: var = expression;

• Here, the type of var must be compatible with the type of


expression.

29
Dynamic Initialization

• Not only constants are used as initializers, but also Java allows variables to be initialized
dynamically, using any expression valid at the time the variable is declared.

package len;
import java.util.Scanner;
public class DaynInit {
public static void main(String args[])
{ Scanner input=new Scanner (System.in);
double a, b,c;
// c is dynamically initialized
System.out.print("Enter base of triangle\n");
a=input.nextInt();
System.out.print("Enter height of triangle\n"); b=input.nextInt();
c = Math.sqrt((a * a) + (b * b));
System.out.println("Hypotenuse is " + c);
}
}

30
The Scope and Lifetime of Variables

• Java allows variables to be declared within any block, in


addition to at the start of the main( ) method.
• A block is begun with an opening curly brace and ended
by a closing curly brace.
• A block defines a scope. Thus, each time you start a
new block, you are creating a new scope.
• A scope determines what objects are visible to other
parts of your program. It also determines the lifetime of
those objects.

31
The Scope and Lifetime of Variables(cont’d…)
• In Java, the two major scopes are those defined by a class
and those defined by a method.
• The scope defined by a method begins with its opening curly
brace. As a general rule, variables declared inside a scope
are not visible to code that is defined outside that scope.
• when you declare a variable within a scope, you are
localizing that variable and protecting it from unauthorized
access and/or modification.
• the scope rules provide the foundation for encapsulation.

32
The Scope and Lifetime of Variables(cont’d…)
• Scopes can be nested.
• For example, each time you create a block of code,
you are creating a new, nested scope.
• the outer scope encloses the inner scope.
• This means that objects declared in the outer scope
will be visible to code within the inner scope.
• Objects declared within the inner scope will not be
visible outside it.

33
Example: effect of nested scopes

34
Control Statements
• Control statements are the statements which alter the flow of execution
and provide better control to the programmer on the flow of execution.

• In Java control statements are categorized into selection control


statements, iteration control statements and jump control statements.

• Java’s Selection Statements: Java supports two selection statements:


if and switch.

• These statements allow us to control the flow of program execution


based on condition.

35
Decision statement
• Decision making structures have
one or more conditions to be
evaluated.
• Statement or statements that are
executed if the condition is
determined to be true, and
• optionally, other statements to be
executed if the condition is
determined to be false.
36
If statement
• An if statement consists of a Boolean expression followed by one or
more statements.
• Following is the syntax of an if statement −

• If the Boolean expression evaluates to true then the block of code


inside the if statement will be executed.
• If not, the first set of code after the end of the if statement (after the
closing curly brace) will be executed.
37
Switch statements

• A switch statement allows a


variable to be tested for equality
against a list of values.

• Each value is called a case, and


the variable being switched on is
checked for each case.

38
Switch statements…

• The following rules apply to a switch statement −

⁻ The variable used in a switch statement can only be integers, convertable


integers (byte, short, char), and strings.

⁻ You can have any number of case statements within a switch

⁻ The value for a case must be the same data type as the variable in the switch
and it must be a constant.

⁻ When the variable being switched on is equal to a case, the statements


following that case will execute until a break statement is reached.

39
Switch statements…

⁻ When a break statement is reached, the switch terminates, and


the flow of control jumps to the next line following the switch
statement.

⁻ A switch statement can have an optional default case, which


must appear at the end of the switch.

⁻ The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.

40
Switch Statement(cont’d…)

41
Loop statements
• There may be a situation when you need to execute a block of code
several number of times. In general, statements are executed
sequentially:

• The first statement in a function is executed first, followed by the


second, and so on.

• A loop statement allows us to execute a statement or group of


statements multiple times
42
while loop
• A while loop statement in Java programming language repeatedly
executes a target statement as long as a given condition is true.
• The syntax of a while loop is −

• Statement(s) may be a single statement or a block of statements.


• The condition may be any expression, and true is any non zero value.
• When executing, if the boolean_expression result is true, then the
actions inside the loop will be executed. This will continue as long as
the expression result is true.
• When the condition becomes false, program control passes to the line 43
while loop…

44
do...while loop

• A do...while loop is similar to a while loop, except that a do...while


loop is guaranteed to execute at least one time.

• The Boolean expression appears at the end of the loop, so the


statements in the loop execute once before the Boolean is tested.
• If the Boolean expression is true, the control jumps back up to do
statement, and the statements in the loop execute again. This process
repeats until the Boolean expression is false.

45
do...while loop

46
For loop
• A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to be executed a specific number of
times.

• A for loop is useful when you know how many times a task is to be
repeated.

• The syntax of a for loop is −

47
For loop…
• Here is the flow of control in a for loop −
• The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables and this step ends with a semi colon (;).
• Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it
is false, the body of the loop will not be executed and control jumps to the next statement
past the for loop.
• After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank with a semicolon at the end.
• The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.
48
For loop…

49
Break and continue statement
• The break statement in Java programming language has the following
two usages −
⁻ When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
⁻ It can be used to terminate a case in the switch statement (covered in
the next chapter).
• The continue keyword can be used in any of the loop control structures.
It causes the loop to immediately jump to the next iteration of the loop.
⁻ In a for loop, the continue keyword causes control to immediately
jump to the update statement.
⁻ In a while loop or do/while loop, control immediately jumps to the
Boolean expression.
50
Defining Classes and Objects
• The most important thing to understand about a class is that it defines
a new data type.

• Once defined, this new type can be used to create objects of that type

• Thus, a class is a template for an object, and an object is an instance of


a class.

• Because an object is an instance of a class, you will often see the two
words object and instance used interchangeably.
51
Class Definition(cont’d…)

• When you define a class, you declare its exact form and nature.
• You do this by specifying the data that it contains and the code that
operates on that data.

• The data, or variables, defined within a class are called instance


variables.

• The code is contained within methods.

• Collectively, the methods and variables defined within a class are


called members of the class.
52
Simple Class

• As stated, a class defines a new type


of data. In this case, the new data
type is called Box.
• You will use this name to declare
objects of type Box.
• It is important to remember that a
class declaration only creates a
template; it does not create an actual
object.
• Thus, the code found at right side
does not cause any objects of type
Box to come into existence.
53
Simple Class…
• To actually create a Box object, you will use a statement like the following:
• Box mybox = new Box(); // create a Box object called mybox
• After this statement executes, mybox will be an instance of Box.
• Each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class.
• Thus, every Box object will contain its own copies of the instance variables
width, height, and depth.
• To access these variables, you will use the dot (.) operator.
• The dot operator links the name of the object with the name of an instance
variable. For example, to assign the width variable of mybox the value 100,
you would use the following statement: mybox.width = 100;

54
Declaring Objects
• when you create a class, you are creating a new data type.
• you can use this type to declare objects of that type.

• obtaining objects of a class is a two-step process.

• First, you must declare a variable of the class type. This variable
does not define an object. Instead, it is simply a variable that can
refer to an object.

55
Declaring Objects…
• Second, you must acquire an actual, physical copy of the object
and assign it to that variable.

• You can do this using the new operator.

• The new operator dynamically allocates memory for an object


and returns a reference to it.

• This reference is the address in memory of the object allocated


by new.
56
Declaring Objects…

57
Declaring Object(cont’d…)
• An object has a unique identity, state, and behavior.
• The state of an object (also known as its properties or attributes) is
represented by data fields with their current values.
• For example, A circle object has a data field radius, which is the
property that characterizes a circle.
• The behavior of an object (also known as its actions) is defined by
methods.
• To invoke a method on an object is to ask the object to perform an
action.
• For example, you may define a method named getArea() for circle
objects. A circle object may invoke getArea() to return its area.
58
Access modifier

• Private members can be accessed only from the inside of the class.

• Public members can be accessed from any other classes.

• Often it is desirable to allow subclasses to access data fields or


methods defined in the superclass, but not allow non-subclasses to
access these data fields and methods. To do so, you can use the
protected keyword.

• A protected data field or method in a superclass can be accessed in


its subclasses
59
Introducing Methods
• A method is a block of code or collection of statements or a set
of code grouped together to perform a certain task or operation.
• It is used to achieve the reusability of code
• We write a method once and use it many times.
• We do not require to write code again and again.
• It also provides the easy modification and readability of code,
just by adding or removing a chunk of code.
• The method is executed only when we call or invoke it.

60
Method Declaration

• The method header specifies the modifiers, return value type, method
name, and parameters of the method.

• The return Type is the data type of the value the method returns.

• Some methods perform desired operations without returning a value.


• In this case, the returnValueType is the keyword void.

• If a method returns a value, it is called a value returning method,


otherwise it is a void method.
61
Method Declaration…
• The variables defined in the method header are known as formal
parameters or simply parameters.

• A parameter is like a placeholder. When a method is invoked, you pass


a value to the parameter.
• This value is referred to as an actual parameter or argument.

• The parameter list refers to the type, order, and number of the
parameters of a method.
62
Method Declaration…
• The method name and the parameter list together constitute the method
signature.

• Parameters are optional; that is, a method may contain no parameters.

• In creating a method, you define what the method is to do.

• To use a method, you have to call or invoke it.

• Calling method means using that method to perform the defined tasks
for that method.
63
Method Declaration…

64
Types of method

 predefined methods are the method that is already defined in the Java class
libraries.
• It is also known as the standard library method or built-in method.
• We can directly use these methods just by calling them in the program at any
point.
• Some pre-defined methods are length(), equals(), compareTo(), etc.
• When we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already
stored in the library.
User-defined Method
• The method written by the user or programmer is known as a user-
65
defined method. These methods are modified according to the requirement.
Passing Parameters
• The power of a method is its ability to work with parameters.
• When calling a method, you need to provide arguments, which must
be given in the same order as their respective parameters in the method
signature. This is known as parameter order association.
• For example, the following method prints a message n times:

66
Constructors

• In Java a constructor is a block of codes similar to the method. It is called


when an instance of the class is created.
• At the time of calling constructor, memory for the object is allocated.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• Java compiler calls a default constructor if there is no constructor
available in the class.
Note: It is called constructor because it constructs the values at the
time of object creation.
67
Inheritance and Polymorphism

Inheritance Basics
• Acquiring the properties from one class to another class
• Producing new class from already existing class.
• Reusability of code is main advantage of inheritance
• To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword.
• The general form of a class declaration that inherits a superclass is
shown here:

68
Inheritance Basics(cont’d…)

• You can only specify one superclass for any subclass that you create.
• Java does not support the inheritance of multiple super classes into a
single subclass.
• You can create a hierarchy of inheritance in which a subclass
becomes a superclass of another subclass. However, no class can be a
superclass of itself.
• Although a subclass includes all of the members of its superclass,
it cannot access those members of the superclass that have been
declared as private.
• A class member that has been declared as private will remain private
to its class.
• It is not accessible by any code outside its class, including subclasses.
69
Using the super Keyword

• The keyword super refers to the superclass of the class in which


super appears. It can be used in two ways:
• To call a superclass constructor.

• The second is used to access a member of the superclass that has been
hidden by a member of a subclass

• The statement super() invokes the no-arg constructor of its


superclass, and the statement super(arguments) invokes the
superclass constructor that matches the arguments.
70
Using the super Keyword(cont’d…)
• The statement super() or super(arguments) must appear in the
first line of the subclass constructor; this is the only way to
explicitly invoke a superclass constructor
• You must use the keyword super to call the superclass constructor.
Invoking a superclass constructor’s name in a subclass causes a
syntax error.
• A constructor is used to construct an instance of a class.
• Unlike properties and methods, the constructors of a superclass are
not inherited in the subclass.
• They can only be invoked from the constructors of the subclasses, using
the keyword super.

71
Polymorphism

Overloading Methods

• In Java it is possible to define two or more methods within the same


class that share the same name, as long as their parameter
declarations are different.

• When this is happened, the methods are said to be overloaded, and


the process is referred to as method overloading.

• When an overloaded method is invoked, Java uses the type and/or


number of arguments as its guide to determine which version of the
overloaded method to actually call.
72
Overloading Methods(cont’d…)

• Thus, overloaded methods must differ in the type and/or


number of their parameters.

• While overloaded methods may have different return types,


the return type alone is insufficient to distinguish two versions
of a method.

• When Java encounters a call to an overloaded method, it


simply executes the version of the method whose parameters
match the arguments used in the call.
73
Method Overriding

• Overridden methods allow Java to support run-time


polymorphism.

• Polymorphism is essential to object-oriented programming for


one reason:
• it allows a general class to specify methods that will be common to
all of its derivatives, while allowing subclasses to define the specific
implementation of some or all of those methods.

74
Method Overriding(cont’d…)

• Method overriding means when a subclass inherits methods from a


superclass.

• Sometimes it is necessary for the subclass to modify the implementation of


a method defined in the superclass.
• This is referred to as method overriding.

• In a class hierarchy, when a method in a subclass has the same name


and type signature as a method in its superclass,
• then the method in the subclass is said to override the method.
75
Method Overriding(cont’d…)

• When an overridden method is called from within its


subclass, it will always refer to the version of that method
defined by the subclass.

• The version of the method defined by the superclass will be


hidden.

• Method overriding occurs only when the names and the type
signatures of the two methods are identical. If they are not,
then the two methods are simply overloaded.
76
Abstract class

• Sometimes you will want to create a superclass that only defines a


generalized form that will be shared by all of its subclasses,
leaving it to each subclass to fill in the details.

• One way this situation can occur, is when a superclass is unable to


create a meaningful implementation for a method.

• To declare a class abstract, you simply use the abstract keyword


in front of the class keyword at the beginning of the class
declaration.
77
Abstract class(cont’d…)

• There can be no objects of an abstract class.


• That is, an abstract class cannot be directly instantiated with the
new operator.
• Such objects would be useless, because an abstract class is not fully
defined.
• An abstract method is defined without implementation. Its
implementation is provided by the subclasses. Abstract method is
defined as
• abstract type name(parameter-list);

78
Interfaces
• using interface, you can specify what a class must do, but not how it
does it.

• Once it is defined, any number of classes can implement an interface.

• One class can implement any number of interfaces.

• To implement an interface, a class must create the complete set of


methods defined by the interface.
• However, each class is free to determine the details of its own
implementation
79
Defining an Interface
• An interface is defined much like a class.
• This is a simplified general form of an interface:
access interface name {

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

//…

return-type method-nameN(parameter-list);

type final-varnameN = value;

80
Defining an Interface(cont’d…)
• When it is declared as public, the interface can be used by any other code.

• In this case, the interface must be the only public interface declared in the
file, and the file must have the same name as the interface. name is the name
of the interface, and can be any valid identifier.

• The methods that are declared in interface have no bodies. They end with a
semicolon after the parameter list.

• They are, essentially, abstract methods; there can be no default


implementation of any method specified within an interface. Each class that
includes an interface must implement all of the methods.
81
Interface definition(cont’d…)
• Variables can be declared inside of interface declarations.

• They are implicitly final and static, meaning they cannot be


changed by the implementing class. They must also be initialized.

• All methods and variables are implicitly public.

• Here is an example of an interface definition.


interface Callback {

void callback(int param);

}
82
Implementing Interfaces

• Once an interface has been defined, one or more classes can implement
that interface.

• To implement an interface, include the implements clause in a class


definition, and then create the methods defined by the interface.

• The general form of a class that includes the implements clause looks
like this:
class classname [implements interface [,interface…]] {

// class-body

83
Casting
• It is about converting one data type into another data type
• Type cast operator is used to convert one data type into
another data type.
• Data type represents the type of the data stored into a variable.
• There are two kinds of data types:
 Primitive Data type: Primitive data type represents singular
values.
• e.g.: byte, short, int, long, float, double, char, boolean.

84
Constructors…
• The following are rules used to define the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and
synchronized

• Like regular methods, constructors can be overloaded (i.e., multiple


constructors can have the same name but different signatures),
• This make it easy to construct objects with different initial data values.
85
static variable

• If you declare any variable as static, it is known as a static


variable.
• The static variable can be used to refer to the common
property of all objects (which is not unique for each object), for
example, the company name of employees, college name of
students, etc.
• It gets memory only once in the class area at the time of class
loading.
• It makes your program memory efficient (i.e., it saves
memory).

86
Static Method

• Sometimes a method performs tasks that does not depend on an object


• Such methods applies to the class in which it is declared as a whole
and it is known as static methods
• To declare a method as static, place keyword static before the return
type in method declaration.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an
instance of a class.
• A static method can access static data member and can change the
value of it.

87
Final keyword
• The final keyword in java is used to restrict the user. The java
final keyword can be used in many context. Final can be:
Java final variable
• If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Java final method
• If you make any method as final, you cannot override it.
Java final class
• If you make any class as final, you cannot extend it.

88
this Keyword
• As you know, it is illegal in Java
to declare two local variables
with the same name inside the
same or enclosing scopes.
• Interestingly, you can have local
variables, including formal
parameters to methods, which
overlap with the names of the
class’ instance variables.
• However, when a local variable
has the same name as an instance
variable, the local variable hides
the instance variable
89

You might also like