• No results found

100 Minute Java

N/A
N/A
Protected

Academic year: 2021

Share "100 Minute Java"

Copied!
295
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

 History of Java  Features of Java  J2SE, J2EE, J2ME

 Difference between Procedure oriented and Object oriented languages (Also Object based language)

 JDK, JVM, JRE  Java Bytecode

Before we start with Object Oriented Features, you should know...

(3)

 Octal and Hexadecimal representation of numbers.  Unicode representation of characters (char).

 Naming conventions

 Arrays and its methods.

 Control statements and Iteration statements - if - else (different forms)

- switch - case - for loop

- while loop - do while loop

- break, continue, label

- labeled break, labeled continue, return Things you should know...

(4)

 Installing JDK, Setting path, compiling and running simple Java Program.

 Whitespace, Comments

 Identifiers, keywords and Literals  Data types

 Operators – (their precedence and associativity) - Arithmetic - Assignment - Arithmetic-Assignment - Relational - Bitwise - Boolean logical

- Short circuit logical - Ternary

(5)

Installing JDK

JDK stands for Java Development Kit.

A software development package from Sun Microsystems that implements the basic set of tools needed to compile, test and debug Java applications and applets.

It contains tools such as javac, java, appletviewer etc. Set PATH in Environment Variable as -

<Drive-Name>\<JDK directory-name>\bin e.g.: C:\Jdk1.4\bin

(6)

Execution cycle of ‘C’ Program

FirstProgram.c

(7)

Execution cycle of Java Program

Source file File in ByteCode format

FirstProgram.java FirstProgram.class

Compiler (javac) converts it into byteCode.

JVM uses this for execution.

(8)

Simplest Java Program

class FirstProgram {

public static void main(String args[]) {

System.out.println("Hello World"); }

}

You can not write ‘C’ program without main().

Similarly, you can not write Java program without “class”. We will study about “Class” in detail in

(9)

Compiling and running Java Program

Go to Command Prompt :

To compile the Java Program

-javac <FileName with Extension>

e.g:- javac FirstProgram.java

To run the Java Program

-java <ClassName>

e.g:- java FirstProgram

Initially keep FileName and ClassName same. Later we will study about the correlation between

(10)

Using EditPlus

You can use EditPlus to write and execute Java program. You can also use EditPlus for programs in different

languages like – C, C++, HTML, JavaScript, VBScript, JSP, Perl, PHP, CSS, XML, C#.

For this follow below instructions –

Tools --> Configure User Tools --> Add Tool

Initially always use Command Prompt to execute Java programs. If you use EditPlus, then you tend to forget syntax of javac and java commands.

(11)
(12)
(13)

WhiteSpace

ASCII space, horizontal tab or form feed and terminators are considered as whitespaces.

Java is a free-form language. This means you need not follow any indentation rules. You can even write an entire program on one line, and still execute it successfully.

A Java program is a free-format sequence of characters that is tokenized by the compiler (broken into a stream of tokens) for further analysis.

White spaces help not only in separating tokens, but also in

formatting the program so that it is easy to read. The compiler ignores the white spaces once the tokens are identified.

(14)

Identifiers

Identifiers are used for class names, method names and variables names.

• It may be any descriptive sequence of characters (uppercase and lowercase), numbers, _ (underscore) and dollar sign.

• They should not begin with numbers.

i.e.: A-Z, a-z, 0-9, _ , $

(15)

Literals

A constant value in Java is created by using a literal representation.

500 88.2 ‘S’ “Welcome”

Integer Floating-point Character String

Java also has escape sequences. Study various characters escape sequences in Java.

(16)

Comments

/* This is traditional multi-line comment */

You can not have nested multi-line comments.

// Single line comment

These are single line comments.

/**

* This is JavaDoc comment. */

(17)

Keywords in Java

Apart from these 49 keywords, Java Language Specification also has 3 reserved words - null, true, and false as literal

values (sometimes referred to as manifest constants) and not keywords.

(18)

class Foo {

public int break(int b) {

System.out.print(“break something”); }

You should know significance and usage of each of the keyword in the above list.

You might be tempted to think - include, overload, unsigned, virtual, friend - are Java keywords, but in fact they are not !! Remember - "Java is not C / C++."

(19)

class Foo {

public int break(int b) {

// code that appears to break something }

}

break is a reserved word and can not be used as a method name.

(20)

Ranges of Primitive Data Type

(21)
(22)

Home Work

Study various Operators in Java, namely –

Arithmetic, Assignment, Arithmetic-Assignment, Relational, Bitwise, Boolean logical, Short circuit logical, Ternary.

(23)

Look for numeric literals that include a comma, for example,

int x = 25,343; // Won't compile because of the comma

Remember this is Java and not C:

int x = 1; if (x) { } // Compiler error!

In Java, condition has to be boolean int x =1;

while (x) { } // Won’t compile; x is not a boolean while (x = 5) { }

//Won’t compile; resolves to 5 (result of assignment)

while (x == 5) { } // Legal, equality test while (true) { } //Legal

(24)

Remember, characters are just 16-bit unsigned integers under the hood. That means you can assign a number literal, assuming it will fit into the unsigned 16-bit range (65535 or less).

For example, the following are all legal: char a = 0x892; // octal literal

char b = 982; // int literal

char c = (char) 70000; // The cast is required; 70000 is out of char range

char d = (char) -98; // Ridiculous, but legal

And the following are not legal and produce compiler errors: char e = -29; // Possible loss of precision; needs a cast

(25)

class TestMain {

public static void main (String [] args) {

System.out.println("First arg is :" + args[0]); }

}

Unlike C++,

+

operator is overloaded by default, you need not write any code for this.

When invoked at the command line as follows,

java TestMain Hello

the output is - First arg is : Hello

(26)

• args[0] is first argument supplied and not the program name (Java is not ‘C’).

• The String array parameter does not have to be named args or arg. It can be named anything (of course excluding

keywords and following variable declaration rules).

Remember that the main argument is just an array! There’s nothing special about it, other than how it gets passed into main (i.e. from the JVM).

(27)

int str = 2;

String i = “Hello”;

System.out.println(str); System.out.println(i);

(28)

Arithmetic Operators

Division Assignment /= Multiplication Assignment *= Subtraction Assignment -= Addition Assignment +=

Decrement (pre - post)

--Increment (pre – post) ++ Modulus % Division / Multiplication *

Subtraction (also unary minus)

-Addition +

Description Operator

(29)

Bitwise Operators

Left Shift assignment <<=

Right Shift Zero fill assignment >>>=

Right Shift assignment >>= X-OR assignment ^= OR assignment |= AND assignment &= Left Shift <<

Right Shift Zero fill >>> Right Shift >> X-OR ^ OR | AND & Unary NOT ~ Description Operator

(30)

Relational Operators

Less than or equal to <=

Greater than or equal to >= Less than < Greater than > Not Equal to != Equal to (Equality) == Description Operator

(31)

Boolean Logical Operators

Ternary ? : Logical NOT ! Short-circuit AND && Short-circuit OR || Logical X-OR ^ Logical OR | Logical AND & Description Operator

(32)

• Can we have different Java Source file name and Class Name ? If yes, then how to compile and run the program?

• If we do not provide command-line arguments in main()

method, then will the String array args[] be empty or null ?

Coffee Cram

• What will be the output of: 5/0, -5/0, 5%0, 5.0/0, 5.0%0 ?

• What will be the output of – System.out.println(1+2+“3”); System.out.println(“1”+2+3);

(33)

byte b1 = 2; byte b2 = 3;

byte b3 = b1+b2;

System.out.println(b3); Find the Output

-Coffee Cram

byte b1 = 2; byte b2 = 3; b1+=b2;

(34)

Widening and Narrowing Conversions

The compiler won’t let you put a value from a large cup into a small one.

But what about the other way round - Pouring contents of small cup into a big one? No ProblemNo Problem !!

byte

(35)

• Converting from a broader data type to a narrower one is called as narrowing primitive conversion.

• Explicit typecast is required.

• This can result in loss of precision.

• Converting from narrower data type to broader one is called as widening primitive conversion.

• This is automatic.

• There is no loss of precision.

(36)

All the conversions between char, byte and short are considered as narrowing conversions. So they can

result in loss of precision.

(37)

Unary numeric promotion

• If the single operand of the operator has a type narrower than int, it is converted to int by an implicit widening primitive

conversion; otherwise, it is not converted. Binary numeric promotion

Binary numeric promotion implicitly applies appropriate widening primitive conversions so that a pair of operands have the broadest numeric type of the two (which is always at least int).

Given T to be the broadest numeric type of the two operands, the operands are promoted as follows

:-• If T is broader than int, both operands are converted to T; otherwise, both operands are converted to int.

(38)

Object Oriented

Features

(39)

1. Abstraction

• Essential element of an object oriented programming. • You can manage complexity thorough an abstraction.

• Consider Car as an object. You do not think of a car as set of thousand individual parts (or sub-systems - like brakes, engine, clutch, gears etc…) rather it is well defined object having unique behavior.

• With abstraction you can drive the car ignoring the details of how the engine, transmission and braking system works. Instead you are free to use the ‘Car’ object as a whole.

(40)

1. Encapsulation

• Mechanism that binds together the code and data it manipulates, and keeps both safe from

outside interference and misuse.

• In Java, basis of an encapsulation is the Class. It is a protective wrapper around the code and data.

• Encapsulation can be achieved, using appropriate access modifiers. Like private variables cannot be accessed from outside the class.

(41)

class Student {

private int age;

private String name;

public int getAge() { return age; } public void setAge (int a)

{ /* Validations here… */ age = a; }

public String getName() { return name; } public void setName(String str)

{

/* Validations here… */ name = str; }

(42)

• Inheritance is the process by which one object acquires the properties of another object. Thus in a class

hierarchy, two classes are formed - superclass and a subclass.

• The class whose properties are inherited is known as Superclass. And the class who does the inheritance is

3. Inheritance

Vehicle

2 Wheeler 3 Wheeler 4 Wheeler

Bike Scooter

IS – A

(43)

Engine Chassis Steering Wheel Has – A relationship

Containment Hierarchy - Aggregation

• In Has-A relationship, composite object is built from other constituent objects that are its parts.

(44)

4. Polymorphism

• Polymorphism (In Greek – Poly means many and morphos means forms) is the ability of different objects to respond to the same message in different ways.

• Polymorphism helps us to design extensible software as we can add new objects to the design without rewriting existing procedures.

• Polymorphism in Java is achieved by Overloading and Overriding.

(45)

Move ( ) Move ( ) Move ( )

Move ( )

Invoking move() method on different objects, would produce different results differing in speed.

(46)

Shape Square Circle name getName( ) calculateArea( ) side calculateArea( ) radius calculateArea( )

Polymorphism : How is it useful ?

Shape Triangle Circle name getName( ) calculateArea( ) base height Square

Adding new class becomes easy with inheritance and polymorphism

(47)

Object oriented approach helps –

- To handle the complexity of software development through Abstraction.

- In generation of Extensible Systems.

- To avoid duplicate code. Use of Inheritance allows us to put common code in one place, and let the subclasses inherit that code from a superclass. This allows us to define a

common protocol for a group of classes.

(48)
(49)

 Class forms the basis of object oriented programming.  You can not write a Java program without Class.

 Class defines a new data type. Something similar to structure in ‘C’.

 Class is a template (or blueprint) for an object and Object is an instance of the Class.

 The words Object and Instance are often used interchangeably.

 An object can be a tangible, intangible or a conceptual entity.

(50)

 A Class denotes a category of objects, and acts as a blueprint for creating such objects.

 A class defines the properties and behaviors for the objects.

 The properties are also called attributes, and are defined by fields in a class.

 The behaviors are also known as operations, and are defined using methods in a class.

(51)

 State

- The state of an object encompasses the current values of all its attributes. An attribute can be static or

dynamic.

 Behavior

- Behavior is how an object acts or reacts, in terms of its state changes and operations performed upon it.

 Identity

- Identity is that property of an object which uniquely identifies the object.

(52)

Color Average Make Power Fuel type Speed Fuel level Tyre pressure Gear Static Dynamic Car Attributes

Values of all attributes at any moment defines the state of the car object

(53)

Open Close Maximize Minimize Resize Move

Total number of operations that can be performed upon a window object and

consequent changes in its state defines behavior of an object

Window Operations

Behavior of an Object

height width position . . . Window Attributes

(54)

Identity

Account number attribute uniquely identifies an account. A single or group of attributes can be identity of an object.

Bank Account

Account Number Balance Interest Rate Customer Name

Identity of an Object

(55)

General form of Class definition: class classname { datatype instance-variable1; datatype instance-variable2; . datatype methodname1(parameter-list) { // method body } datatype methodname2(parameter-list) { // method body } }

Data or variables, defined within a class are called instance

variables. Variables and methods are called as members of class.

(56)

class Student { int rollNo; String name; String course; }

The class declaration only creates a template; it does not create the actual object.

To create the actual object(instance) of this class, you need to write a statement like :

(57)

 Now objStudent is an object (instance) of the class Student. Thus it will have some physical reality.

 Each time you create an instance of this class, you are creating an object that contains its own copy of

instance variables namely - rollNo, name, course  To access these variables you use

.

(Dot) operator objStudent.rollNo = 001;

objStudent.name = “ABC”; objStudent.course = “MCM”;

(58)

 Creating objects of the class is a two step process:

-Step 1 – You must declare a variable of the class type. This is called as a reference variable and it is not the actual

object.

Step 2 – You must acquire a physical, actual copy of that object. For this you use new operator.

 new operator dynamically (at run-time) allocates memory for an object and returns a reference to it. This reference has to be stored in the reference variable.

Student objStudent = new Student();

Declaring Objects

(59)
(60)

objStudent

rollNo name course 2. objStudent = new Student(); 1. Student objStudent;

objStudent null

Stack memory Heap memory

(61)

 There is nothing called Object Variable. There is only an Object reference variable or simply – reference variable.  Reference variable is not the object itself.

 Use of (

.

) DOT operator on this reference variable, is

similar to pressing a button on the remote control to access the actual object (TV).

(62)

Code Section

Data Area

Heap Area

Stack Area

Dynamically allocated Area (Objects)

Static And Global Variables

Local / reference variables

Movable Boundary

Fixed Boundary

(63)

Student objStudent1 = new Student(); Student objStudent2 = new Student();

objStudent1 rollNo name course objStudent2 rollNo name course

(64)

Student objStudent1 = new Student(); Student objStudent2 = objStudent1;

objStudent1

rollNo name course objStudent2

(65)

 Although objstudent1 and objstudent2 refer to the

same object, they are not linked to each other in anyway. objstudent1 = null;

Here objstudent1 is set to null but objstudent2 still refers to the actual object created previously.

rollNo name course objStudent2

reference variable Actual Object

(66)

When you assign one object reference variable to another object reference variable, you are not

creating a copy of the object; you are making a copy of the reference.

You may see the words construct, create, and

instantiate used interchangeably. They all mean – “An object has been built and placed on the heap.”

(67)
(68)

Methods

• Introduction of methods give Java power and flexibility. datatype methodname1(parameter-list)

{

// method body }

• datatype specifies the type of data returned by the method. This can be any valid types including class types. If method

does not return any value, return type is void.

• methodname must be a legal identifier other than those already declared for other items within the current scope.

• paramter-list is the sequence of type and identifier pairs

separated by commas. If no parameters are present, paramter-list can be empty.

• Methods having return type other than void, must have a

(69)

Actual Arguments / Formal Parameters

You might be using the words arguments and parameters interchangeably, but formal Computer Science makes a distinction between them.

Method uses parameters, A caller passes arguments.

Arguments are the things you pass into the methods. And parameters are nothing but local variables for that method. Actual arguments are the values you pass while invoking a method.

(70)

A closer look at Argument passing

There are two ways in which, computer language can pass an argument to a subroutine (function / method).

- Call by value :– This copies the value of an argument into formal parameter of the subroutine. So changes made to the parameters of the subroutine have no effect on the arguments used to call it.

e.g. primitive data types as arguments.

- Call by reference :- Reference to an argument (not the value of argument) is passed to the parameter.

Inside the subroutine, this reference is used to access the actual argument. This means changes made to the parameters will affect the arguments used to call it.

(71)

Recursion

• Java supports recursion.

• Recursion is the process of defining something in terms of itself.

• Recursion allows a method to call itself. Such a method which calls itself is said to be a recursive method.

• Classic example of recursion is to compute factorial of a number.

(72)

New operator dynamically allocates the memory for an object and returns a reference to it.

Syntax:

-Student s = new -Student( );

s = reference variable.

new Student( ) = Actual object.

It calls for the parameter-less constructor of the class Student, if the constructor is explicitly created; otherwise Java creates it’s own constructor, which is called as a default constructor. new operator allocates memory for an object at run-time. This allows a program to create as many as objects needed during its execution. However, since memory is finite, it is possible that new operator will not be able to allocate memory for an object because of the insufficient memory. In such case, program will generate

(73)

Constructor

• Constructor is used to initialize an object immediately after it is created. (Before new operator completes)

• Constructor is used to, initialize the instance variables. • It has the same name as that of the class in which it resides.

• It is syntactically similar to a method.

• Constructor has no return type, not even void. Implicit return type of constructor is the class type itself.

(74)

Constructor

(continued…)

• If you do not define a constructor explicitly, the compiler will create default, parameter-less constructor.

• The default constructor is the constructor provided by the system in the absence of any constructor provided by the programmer. Once a programmer supplies any

constructor whatsoever, the default constructor is no longer supplied by the system.

• A no-argument (parameter-less) constructor, on the other hand, is a constructor provided by the programmer which takes no arguments.

The default constructor is always no-argument (parameter-less) constructor.

(75)

Parameter-less Constructor

class Student { int rollNo; String name; String course; Student() { rollNo = 001; name = “ABC”; course = “MCM”; } } instance variables

(76)

Parameterized Constructor

class Student { int rollNo; String name; String course;

Student(int rollNo, String name, String course) {

rollNo = rollNo; name = name;

course = course; }

(77)

Student objStudent1 = new Student(1,“ABC”,“MCM”);

Student objStudent2 = new Student(2,“PQR”,“MCM”);

‘this’ keyword

• ‘this’ keyword can be used inside any method to refer to the current object.

• ‘this’ is always reference to the object on which the method was invoked.

• When local variable has the same name as that of the

instance variable, it hides the instance variable. But use of ‘this’ lets you resolve any “namespace collisions” that might occur between instance and local variables.

(78)

class Student {

int rollNo; String name; String course;

Student(int rollNo, String name, String course) {

this.rollNo = rollNo; this.name = name;

this.course = course; }

(79)

Coffee Cram

• We studied - what is Class and what is an Object.

To confuse you even more, Java has 2 classes namely – Class and Object   Find out more information about them.

• Can we have a same name for -- Constructor and a method. - Class and a method.

Will it cause any error in the program?

(80)

Coffee Cram

• Can we define local variables (inside a method) with the same name as an instance variables?

• Can we declare method with signature – void MyMethod(void)

(81)

Inheritance

Polymorphism

&

(82)

Inheritance

• Inheritance is one of the important features of object oriented programming.

• It allows creation of hierarchical classifications. • It involves Generalization and Specialization.

• Generalization is creation of general class that defines attributes that are common to set of related classes.

•This generalized class is then inherited by other, more specific classes, each adding attributes unique to it.

• In Java terminology, class that is inherited is called as a superclass (parent) and class that does the inheriting is called as a subclass (child).

(83)

• Subclass is a specialized version of superclass, thus

inherits all of the instance variables and methods defined in superclass and also adds its own unique variables and methods.

(84)

Keyword extends is used to specify use of inheritance – class A { int i=10,j=20; void printij() { System.out.println(“i=”+ i+ “j=”+ j); } } class B extends A { int k=30; void printk() { System.out.println(“k=”+ k); }

(85)

Multilevel Inheritance

• Multilevel Inheritance – You can create an hierarchy that can contain as many inheritance levels as you want. e.g. Given classes – A, B, C, D, where D is subclass of C, which is a subclass of B, which is a subclass of A.

• In such a situation each subclass inherits attributes of all of its superclasses.

A B C D

(86)
(87)

Multiple Inheritance

• Multiple Inheritance – Here a subclass inherits attributes from more than 1 superclass.

• Java does not support multiple inheritance through classes. It supports multiple inheritance through interfaces (we will see this later)

Father

Child

(88)

Superclass reference can refer to Subclass Object

• Superclass reference can refer to Subclass object.

• It is important to understand it is type of the reference variable – not the type of the object it refers to - that

determines what members can be accessed.

• When a Superclass reference refers to the subclass

object, it can access only those parts of the object defined by the superclass.

• This is because the superclass has no knowledge of what a subclass adds to it.

Remember – Subclass reference can not refer to Superclass object.

(89)

• Super is used to invoke the super class constructor, method or variable from sub class.

• Super must be the first statement in the sub class’ constructor or method.

• In the class hierarchy, the constructors are called in the order of derivation, from super class to sub class.

• As super is the first statement during the class, the order will be same whether or not super is used.

• If super is not used, then default parameter-less constructor of each super class will be executed.

(90)

• Second form of ‘Super’ is used to refer to superclass members.

General form : super.member

member could be a suerclass method or a variable.

• This form of super is most applicable to situations in which member names of a subclass hide members by the member names of a subclass hide members by the

same name in superclass same name in superclass.

(91)
(92)
(93)

Inheritance

Polymorphism

&

(94)

Method overloading is one of the ways in which Java implements Static Polymorphism.

In Java, it is possible to overload two or more methods, only if below statements are true:

-• The methods should have different parameters.

• The methods may or may not have different return type.

• Methods should have same name.

• All the methods should be in the same scope (i.e. Within the same class, or parent and child class.)

(95)

When an overloaded method is invoked, java uses the type and / or number of arguments (parameters) to decide which version of the overloaded method to call.

However, return type alone is insufficient to decide which method is to be called.

If, parameters passed satisfy more than one overloaded versions, then most specific method version is called.

(96)

this():

It can be used to call one constructor from the other. The number of parameters, determines which constructor should be called.

this() must be the first statement in the constructor.

Remember – this() and super() can not be in the same constructor.

(97)

class MyClass { MyClass() { System.out.println(“Parameter-less”); } MyClass(int a, int b) {

this(); // It will call parameter-less constructor

System.out.println(“2 Parameter”); }

MyClass(int a, int b, int c)

{

this(a, b); // It will call 2 parameter constructor

System.out.println(“3 Parameter”); }

(98)

Method overriding is the way in which java implements Dynamic Polymorphism.

• Method in a sub class should have same name and

signature (return type and arguments) as the method in the super class.

• When an overridden method is called within the sub class, it will always refer to the version of that method defined by the subclass. The version of the method defined by the super class will be hidden.

• Method overriding occurs only when names and type

signature of two methods are exactly identical otherwise two methods are simply overloaded not overridden.

(99)

• The new method which does the overridding, can not narrow the accessibility of the method but can widen it. • The new method which does the overridding, can only

specify all or none or subset of exception classes (checked exceptions only) specified in the throws clause of the

overridden method in the superclass.

More about Overriding...

We shall study - ‘Accessibility’ and ‘Exceptions’ later, but as of now just make a note of it.

(100)

class A // Super class {

void disp( ) {

System.out.println(“U R in class A”) }

}

class B extends A //Sub class {

void disp( ) {

System.out.println(“U R in class B”) // output }

}

class Main {

public static void main(String args[]) {

B b = new B(); b.disp();

(101)

Call to an overridden method is resolved at run-time, rather than at compile time.

This is known as Dynamic Method Dispatch (Dynamic Polymorphism)

(102)

1. You have two overloaded methods

-void print(long l) and

void print(int i)

and you pass a value 3 as a parameter.

Which method version will be executed? And Why?

(103)

Try out the same program with different method

combinations and pass arguments as – 3, 2.5 and number out of range.

void print(byte b) and void print(int i) void print(byte b) and void print(short s) void print(long l) and void print(short s) void print(long l) and void print(double d) void print(float f) and void print(int i)

void print(float f) and void print(double d)

Coffee Cram

Try as many combinations as you can and note down the results.

(104)

Inheritance

Polymorphism

&

(105)

In dynamic method dispatch, call to an overridden method is resolved at run-time, rather than at compile time.

It is also called as run-time polymorphism or late binding. Super class reference variable can hold sub class object. (Parent can hold child’s object).

When an overridden method is called through a super class reference, Java determines which version of that method to execute based upon the type of the object being

referred.

The type of object being referred to (Not the type of

reference variable) determines which version of method to be called.

(106)

class Main {

public static void main(String args[]) {

A obj = new B(); obj.disp(); }

}

A obj  Type of reference variable.

(107)

• A subclass is a specialization of its superclass ⇒ every instance of the subclass is an instance of the superclass

• The type defined by the subclass is a subtype of the type defined by its superclass.

Shape

Square Circle

Shape

Circle Square

SuperType and SubType

(108)

Upcasting and Downcasting

Upcasting

A subclass reference can be assigned to superclass

reference because, subclass object can be used where a superclass object is used. This is called as upcasting, as references are assigned up the inheritance hierarchy.

Upcasting is automatic. You need not use explicit typecast.

A obj_a = new A(); B obj_b = new B();

(109)

Downcasting

Casting the references of superclass type to subclass type is called as downcasting, as references are assigned down the inheritance hierarchy.

Downcasting is not automatic. You should use explicit typecast. Compiler verifies that an inheritance relationship exists

between the source and destination reference types. However, cast can be invalid at runtime. In such a case, ClassCastException is thrown.

A obj_a = new B(); B obj_b = new B(); B b = (B)obj_a;

A obj_a = new A(); B obj_b = new B(); B b = (B)obj_a;

(110)

instanceof operator has the following syntax :

<reference> instanceof <destination-type>

instanceof operator returns true if the left-hand operand (reference) can be cast to right-hand operand (destination-type), but always returns false if the left-hand operand is null.

if instanceof operator returns true, then the corresponding cast will always be valid.

if instanceof operator returns false, then the cast involving the operands will throw ClassCastException.

(111)

Exam e;

e = new PracticeExam();

PracticeExam pe; pe = new Exam();

Which makes sense and is Legal ?

(112)

• Automatic Promotion

Cat c = new Cat(); Animal a = c;

• Explicit cast required: Animal c = new Cat(); Cat c = (Cat) a;

• Will not compile: Cat c = new Cat(); Dog d = (Dog) c;

(113)
(114)

• static • final

• abstract (we will see this later)

• synchronized (will see this when we study Threads) • native

• transient • volatile

(115)

Instance members (methods or variables) are used in conjunction with an object of the class. However, it is possible to create a member that can be used by itself, without reference to a specific instance.

When, member is declared as static, it can be accessed, before any objects of that class are created.

Both methods and variables can be declared as static. main () method is static because it is called before any object exists.

(116)

Static Variables

• Variables are declared as static essentially global variables.

• When objects of its class are declared, no copy of static variables is made. Instead, all instances of the class share the same static variables.

• All the static variables are initialized to their default values.

Static Methods

• They can call only other static methods. • They must access only static data.

(117)

Static method can be invoked in two ways: Thread t = new Thread();

1. Class.methodname (); e.g. Thread.sleep(100); 2. object.methodname (); e.g. t.sleep(100);

Non-Static method can be invoked only through the object reference:

• object.methodname(); e.g. t.join();

Static methods cannot be overridden, although they can be re-declared / redefined by a

subclass. So even though static methods can sometimes appear to be overridden,

polymorphism rules do not apply. Type of a reference variable decides the method call.

(118)

Understanding Final

The keyword final has 3 uses - final variable, final method and final class

Final variable

• It is equivalent to a named constant.

• It must be initialized during the declaration. • It cannot be re-initialized.

• According to the convention such variables are written in capital letters.

• Blank final variable can be only declared and not initialized, but should be assigned a value either in the constructor or initializer block.

E.g.:

(119)

Final method

• Final method cannot be overridden. • Final method can be overloaded.

• Since final methods are not overridden, call to such methods is resolved at compile time (Early binding)

Final class

• Final class cannot be inherited. • Final class can be instantiated.

• Declaring a class as final implicitly declares all its methods as final too.

(120)

• Native methods are also called as foreign methods. • Their implementation is not defined in Java but in another programming language, for example, C or C++. • Since its implementation appears elsewhere, only the

method prototype is specified in the class definition. The method prototype is prefixed with the keyword native.

• The Java Native Interface (JNI) is a special API that allows Java methods to invoke native functions

implemented in C.

• Method should end with a semicolon. No opening-closing

native

(121)

class Native { /*

* The static block ensures that the native method library

* is loaded before the native method is called. JNI calls this. */

static {

System.loadLibrary("NativeMethodLib"); // (1) Load native library.

}

native void nativeMethod(); // (2) Native method prototype. // ...

}

class Client { //...

public static void main(String[] args) {

Native aNative = new Native();

aNative.nativeMethod(); // (3) Native method call. }

//... }

(122)

• Objects can be stored using serialization.

• Serialization transforms objects into an output format that is helpful for storing objects. Objects can later be retrieved in the same state as when they were serialized, meaning that all fields included in the serialization will

have the same values as at the time of serialization. Such objects are said to be persistent.

• A field can be specified as transient in the class

declaration, indicating that its value should not be saved when objects of the class are written to persistent

storage.

(123)

• Object may not be serializable. Does not implement Serializable interface.

• Object may be relying upon some run-time specific information, so can not be saved.

• Though most of the things in Java are serializable; you can not save things like - network connections, file objects and threads. Because they all are instantiated in a way

that it unique to particular JVM.

(124)

• During execution, compiled code might cache the values of fields for efficiency reasons.

• Since multiple threads can access the same field, it is vital that caching is not allowed to cause inconsistencies when

reading and writing the value in the field.

• The volatile modifier can be used to inform the compiler that it should not attempt to perform optimizations on the field, which could cause unpredictable results when the

field is accessed by multiple threads.

volatile

(125)

Relax

You should only be aware of the modifiers namely – native, transient and volatile.

Now as far MCM syllabus is concerned, you

may not need to try this out practically.

But understanding the significance of these modifiers is important from exam point of view.

(126)

• Can we overload a main() method? Which version of main method gets invoked?

• Can we declare main() method as final ? • Can static methods be overridden?

• Can static methods be overloaded?

Coffee Cram

• Can we have local variables declared as static? • What if static modifier is removed

(127)
(128)

• Packages are containers that allow compartmentalization of classes.

• Packages are a named collection of classes grouped in a directory.

• Packages are a way of grouping related classes & interfaces.

• A package can contain any number of classes that are related in purpose, in scope or by inheritance.

• Convenient for organizing your work & separating your work from code libraries provided by others.

• You can create you own package and store classes inside it without concern that it will collide with some other class

(129)

Part I – Package Statement (Optional)

Part II – Import Statements (Zero or More)

Part III – Definitions of classes or interfaces (Zero or More)

(130)

• Use keyword package at the beginning of the file. • Create a directory of that package name.

• Compile the file and keep the .class files in this directory. • Set the classpath from the root up to the directory

created above.

• Use the import keyword whenever the class in the particular package has to be used.

(131)

• Check current directory.

• Compiler looks through all directories specified in the classpath for

- The actual class file. OR

- The subdirectory that has the name of the imported package.

• Then, looks for the file in one of the imported packages. • Finally looks for file in java.lang package.

• If compiler still does not locate the file, it gives an error.

(132)

• Specific location that Java compiler will consider as the root of any package hierarchy is controlled by CLASSPATH. • If you don’t specify package name, current working

directory (.) is taken by default in the CLASSPATH variable defined by Java run-time environment.

• If you store a class named TestClass in a package named testpack, you should access that class as testpack.TestClass. Or, change CLASSPATH variable.

• If you are working on your source code in a directory named C:\myjava then set your CLASSPATH to:

set CLASSPATH= “. ; C:\myjava ; C:\java\classes”

(133)

package p1; Class A { ... } package p1; class B extends A { ... } package p2; Class C extends p1.B { ... }

(134)

Importing packages

• Java includes the import statement to bring certain classes, or entire packages into visibility.

• Once imported a class can be referred directly, using only its name.

• Either specified class from a particular package can be

accessed or asterisk (*) can be used to import all the classes from that package. But this does not recursively import sub-packages.

E.g:

import java.awt.*;

(135)

If you use * notation for import, rather than importing specific classes that are required, will that affect compile-time and run-time performance of the program ?

When you use * notation, it increases the compilation time, because it includes all the classes from that

package. Hence it is a good idea to mention specific class names. However asterisk (*) notation, has absolutely no

(136)

Public Private No Modifier Protected Same class

 

 

 

Same Package Sub - class

 

 

 

Same Package Non - Sub class

 

 

 

 

Different Package Sub - class

 

 

 

 

Different Package Non - Sub class

 

 

 

 

 

Access Modifiers

***

(137)

Method overriding and access modifiers

• The new method which does the overridding, can not narrow the accessibility of the method but can widen it. • The new method which does the overridding, can only

specify all or none or subset of exception classes (checked exceptions only) specified in the throws clause of the

overridden method in the superclass.

We shall study ‘Exceptions’ later, but as of now just make a note of it.

(138)

You need to know the effect of different combinations of class and member access (such as a default class with a public variable).

To figure this out, first look at the access level of the

class. If the class itself will not be visible to another class, then none of the members will be either, even if the

member is declared public.

Once you’ve confirmed that the class is visible, then it

(139)

• Can we declare main() method as private ? 2. What if main() method is written as

static public void main(String args[]) instead of public static void main(String args[])

3. Can we import same package /class twice? Will the JVM load that package / class twice?

4. Are the imports checked for validity at compile

time? E.g. Will the code containing an import such as java.lang.ABCD compile?

Coffee Cram

(140)

• Can we have more than one public class in Java source file ?

• Can we apply these access modifiers (private, protected, public) to Classes and constructors?

• Can we have multiple classes in the same Java source file? Are package and import statements applicable to all the classes in that source file?

• Would there be any situation where we need to use fully qualified class names rather than importing packages

/classes?

(141)

Abstract Classes

and Interfaces

(142)

What does a new Animal() object look like?

Some classes should not be instantiatedshould not be instantiated. If you

instantiate new Animal() object, what does that mean?

What exactly is an animal object? What shape is it? What color is it? What size is it?

Instantiating Animal class has virtually no use, no meaning,

Animal

Elephant Lion

(143)

• Abstract methods have no implementation specified. • These methods are declared with a prefix abstract.

• It is required that these methods must be overridden by a sub class.

• Otherwise sub class must also be declared as an abstract.

Syntax:- abstract type-name (parameter-list); // no body present.

(144)

Abstract class

• Any class that contains one or more abstract methods must also be declared abstract.

• To declare a class abstract, abstract keyword is used before the class keyword at the beginning of the class

declaration.

• Abstract class cannot be instantiated with the new operator because an abstract class is not fully defined.

• Abstract class can be inherited.

• Abstract constructors or abstract static methods cannot be declared.

(145)

It really sucks to be an abstract method.

You don’t have a body.

Remember : Abstract method has no

body. The method declaration ends with a semicolon.

(146)

An abstract class is incomplete by itself and relies upon its sub classes to provide complete implementations. And

abstract class cannot be instantiated.

Where as, final class cannot be inherited but can be

instantiated.

The compiler, gives compile time error if an attempt is

It is illegal to declare a class as both final and

abstract

(147)

• Using Inheritance, subclass can inherit the code from its superclass.

• But class can not extend more than once class. Java does not support multiple class inheritance.

• The OO language like C++ supports multiple inheritance at the cost of added complexity and ambiguity at times.

• Java supports a single chain of implementation inheritance. • To overcome the lack of multiple inheritance Java uses

Multiple Inheritance using Interfaces.

Interface

(148)

• An Interface is essentially a collection of constants & abstract methods.

• Using an interface, you can specify what a class should do but not how it does it. Interfaces are similar to abstract classes but they do not have any instance variables.

• Interface methods are declared without any body.

• Once defined, any number of classes can implement that interface. Also, a class can implement any number of

interfaces.

• Interface can not be instantiated. However, reference

(149)

Syntax:

access interface name

{

return-type method1 (paramter-list); return-type method2 (paramter-list); type final-varname1 = value;

type final-varname2 = value; }

access: Either public or not used.

interface: Keyword to declare an interface.

name: Name of the interface.

Interface

(continued…)

(150)

• Interface methods have no bodies. They end with a semicolon.

• They are essentially abstract methods. Each class that implements an interface i.e. subclass must override these methods and add some functionality to it.

• Variables can be defined inside an interface, which are implicitly final and static.

• In an interface, all the methods must be public and abstract. (Never static)

• When class inherits an interface, the keyword

implements should be used. But when one interface inherits

(151)

• void bounce();

• public void bounce(); • abstract void bounce();

• public abstract void bounce(); • abstract public void bounce();

• final void bounce(); // final and abstract can never be used • static void bounce(); // interfaces define instance methods • private void bounce(); // interface methods are always public • protected void bounce(); // (same as above)

• synchronized void bounce(); // can’t mix abstract and synchronized

• native void bounce(); // can’t mix abstract and native

(152)

• public int x = 1; // Looks non-static and non-final, but isn’t! • int x = 1; // Looks default, non-final, and non-static, but isn’t! • static int x = 1; // Doesn’t show final or public

• final int x = 1; // Doesn’t show static or public • public static int x = 1; // Doesn’t show final

• public final int x = 1; // Doesn’t show static • static final int x = 1 // Doesn’t show public

• public static final int x = 1; // Exactly what you get implicitly

(153)

• class Foo { } // OK

• class Bar implements Foo { } // No! Can’t implement a class • interface Baz { } // OK

• interface Fi { } // OK

• interface Fee implements Baz { }

// No! Interface can’t implement an interface • interface Zee implements Foo { }

// No! Interface can’t implement a class

(154)

• interface Zoo extends Foo { }

// No! Interface can’t extend a class • interface Boo extends Fi { }

// OK. Interface can extend an interface • class Toon extends Foo, Button { }

// No! Class can’t extend multiple classes • class Zoom implements Fi, Fee { }

// OK. class can implement multiple interfaces • interface Vroom extends Fi, Fee { }

(155)

Coffee Cram

• Can Abstract classes have constructors ? Can they be called using super() ?

• Can an interface have constructors?

• Can an interface be defined as abstract?

e.g. abstract interface MyInterface{}

• Can abstract method be declared as private? • Can an abstract class implement an interface?

(156)

Initializer

Blocks

(157)

Initializers means initialization of fields in the classes. i.e. fields being assigned initial values.

These initializers are

-• field initializer expressions • static initializer blocks

• instance initializer blocks

(158)

• Initialization of fields can be explicitly specified in field

declaration statements using initializer expressions. The value of the initializer expression must be assignment compatible to the declared field.

class ConstantInitializers {

int minAge = 12; // Non-static static double pensionPoints = 10.5; // (2) Static // ...

}

• Since a class is always initialized before it can be instantiated, an instance initializer expression can always refer to any static member of a class, regardless of the member declaration order.

Forward reference in the following code is perfectly legal.

class MoreInitializers {

int noOfDays = 7 * NO_OF_WEEKS; // (1) Non-static static int NO_OF_WEEKS = 52; // (2) Static

(159)

• Java requires that the declaration of a field must occur before its usage in any initializer expression, if the field is used on the right-hand side of an assignment in the initializer expression.

• This essentially means that the declaration of a field must occur before the value of the field is read in an initializer expression. Using the field on the left-hand side of an assignment in the

Using the field on the left-hand side of an assignment in the

initializer expression does not violate the declaration-before-read

initializer expression does not violate the declaration-before-read

rule

rule, as this constitutes a write operation.

class NonStaticInitializers { int length = 10;

double area = length * width; // Not Ok. Illegal forward reference.

double area = length * this.width; // Ok, but width has default value 0.

int width = 10;

int sqSide = height = 20; // OK. Legal forward reference. int height;

(160)

• Java allows static initializer blocks to be defined in a class. Although such blocks can include arbitrary code, they are

primarily used for initializing static fields. The code in a static initializer block is executed once only when the class is

initialized.

• Note that the static initializer block is not contained in any method. A class can have more than one static initializer block. Initializer blocks are not members of a class, nor can they have a return statement, as they cannot be called directly.

• When a class is initialized, the initializer expressions in static field declarations and static initializer blocks are executed in the order they are specified in the class.

(161)

class StaticForwardReferences {

static { // (1) Static initializer block

sf1 = 10; // (2) OK. Assignment to sf1 allowed

sf1 = if1; // (3) Not OK. Non-static field access in static context int a = 2 * sf1; // (4) Not OK. Read operation before declaration

int b = sf1 = 20; // (5) OK. Assignment to sf1 allowed

int c = StaticForwardReferences.sf1;// (6) OK. Not accessed by simple name }

static int sf1 = sf2 = 30; // (7) Static field. Assignment to sf2 allowed static int sf2; // (8) Static field

int if1 = 5; // (9) Non-static field

static { // (10) Static initializer block

int d = 2 * sf1; // (11) OK. Read operation after declaration int e = sf1 = 50; // (12)

}

public static void main(String[] args) {

System.out.println("sf1: " + StaticForwardReferences.sf1); System.out.println("sf2: " + StaticForwardReferences.sf2); }

(162)

• The code in the local block is executed every time an instance of the class is created.

• instance initializer block is not contained in any method. A class can have more than one instance initializer block, and

these (and any instance initializer expressions in instance field declarations) are executed in the order they are specified in the class.

• instance initializer block cannot make a forward reference to a field that violates the declaration-before-read rule.

(163)

class NonStaticForwardReferences {

{ // (1) Instance initializer block

nsf1 = 10; // (2) OK. Assignment to nsf1 allowed

nsf1 = sf1; // (3) OK. Static field access in non-static context

int a = 2 * nsf1; // (4) Not OK. Read operation before declaration

int b = nsf1 = 20; // (5) OK. Assignment to nsf1 allowed int c = this.nsf1; // (6) OK. Not accessed by simple name

}

int nsf1 = nsf2 = 30; // (7) Non-static field. Assignment to nsf2 allowed int nsf2; // (8) Non-static field

static int sf1 = 5; // (9) Static field

{ // (10) Instance initializer block

int d = 2 * nsf1; // (11) OK. Read operation after declaration

int e = nsf1 = 50; // (12) }

public static void main(String[] args) {

NonStaticForwardReferences objRef = new NonStaticForwardReferences(); System.out.println("nsf1: " + objRef.nsf1);

System.out.println("nsf2: " + objRef.nsf2); }

(164)

• Static variable initialization

• Static initializer blocks execution (in the order of declaration if multiple blocks are present)

• Constructor header (super – implicit / explicit)

• Instance variables initialization / instance initializer blocks execution.

• Rest of the code in the constructor.

(165)

1. Can we print some message on the console without writing a main() method? If yes, how ?

(166)

References

Related documents

If your company performs regular, periodic calibrations on a high volume of instruments across a plant, then documenting calibrators can help reduce costs, time and effort,

Page2/32 SPACE FOR ROUGH WORK / Sample Test Paper-1..   This section contains

Finally, by performing the hits of the West End at the imperial periphery, touring companies not only allowed colonial audiences to participate in the metropolitan culture, but

Among both those visitors who had visited a museum in San Antonio in the past 12 months or planned to do so in the next six, seeing friends or relatives as well as going to

Reversibility of the anticoagulant effect of high doses of the direct thrombin inhibitor dabigatran, by recombinant factor VIIa or activated prothrombin complex concentrate.. van

Figure 4: Continuous Ranked Probability Skill Score versus lead time for the TIGGE-4 multi-model (solid line), for the contributing single-models itself (dotted

Oscar and Discovery Vitality show that health insurers can profit from digital fitness tracking programs in three ways:.  Customer acquisition through marketing