1 of 79

Module 1:� Introducing Classes �

2 of 79

Introduction:

Class Fundamentals

  • 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.

or

A class is a group of objects which have common properties .

  • The General Form of a Class:
  • A class is declared by use of the class keyword. The classes that have been used up to this
  • A simplified general form of a class definition is shown here:

​

2

3 of 79

class classname {

type instance-variable1;

type instance-variable2;

// ...

type instance-variableN;

type methodname1(parameter-list) {

// body of method

}

type methodname2(parameter-list) {

// body of method

}

// ...

type methodnameN(parameter-list) {

// body of method

}

}

3

4 of 79

A Simple Class�

  • Here is a class called Box that defines three instance variables: width, height, and depth. Currently, Box does not contain any

methods (but some will be added soon).

class Box {

double width;

double height;

double depth;

}

  • 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.

4

5 of 79

  • Thus, the preceding code does not cause any objects of type Box to come into existence.
  • To actually create a Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

mybox will be an instance of Box. Thus, it will have “physical” reality.

  • 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;

​

​

5

6 of 79

��/* A program that uses the Box class.�

class Box {

double width;

double height;

double depth;

}

// This class declares an object of type Box.

class BoxDemo {

public static void main(String args[]) {

Box mybox = new Box();

double vol;

// assign values to mybox's instance variables

mybox.width = 10;

mybox.height = 20;

mybox.depth = 15;

// compute volume of box

vol = mybox.width * mybox.height * mybox.depth;

System.out.println("Volume is " + vol);

}

}

6

7 of 79

// This program declares two Box objects.�

class Box {

double width;

double height;

double depth;

}

class BoxDemo2 {

public static void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// assign values to mybox1's instance variables

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

​

7

8 of 79

/* assign different values to mybox2's

instance variables */

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// compute volume of first box

vol = mybox1.width * mybox1.height * mybox1.depth;

System.out.println("Volume is " + vol);

// compute volume of second box

vol = mybox2.width * mybox2.height * mybox2.depth;

System.out.println("Volume is " + vol);

}

}

8

9 of 79

Declaring Objects

  • 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.
  • 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 (that is, allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object
  • allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.

9

10 of 79

  • A line similar to the following is used to declare an object of type Box:

Box mybox = new Box();

  • This statement combines the two steps just described. It can be rewritten like this to show each step more clearly:

Box mybox; // declare reference to object

mybox = new Box(); // allocate a Box object

10

11 of 79

A Closer Look at new�

  • As just explained, the new operator dynamically allocates memory for an object. It has this
  • general form:
  • class-var = new classname( ); mybox=new Box;

​

11

12 of 79

Assigning Object Reference Variables�

  • Object reference variables act differently than you might expect when an assignment takes

place.

Box b1 = new Box(); a1=10;

a2=a1;

Box b2 = b1;

​

12

13 of 79

Introducing Methods

The general form of a method:

type name(parameter-list) {

// body of method

}

Adding a Method to the Box Class

// This program includes a method inside the box class.

class Box {

double width;

double height;

double depth;

// display volume of a box

void volume() {

System.out.print("Volume is ");

System.out.println(width * height * depth); } }

13

14 of 79

class BoxDemo3 {

public static void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

// assign values to mybox1's instance variables

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

/* assign different values to mybox2's

instance variables */

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// display volume of first box

mybox1.volume();

// display volume of second box

mybox2.volume(); } }

14

15 of 79

Returning a Value(// Now, volume() returns the volume of a box.)

class Box {

double width;

double height;

double depth;

// compute and return volume

double volume() {

return width * height * depth;

}

}

class BoxDemo4 {

public static void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

15

16 of 79

// assign values to mybox1's instance variables

mybox1.width = 10;

mybox1.height = 20;

mybox1.depth = 15;

/* assign different values to mybox2's

instance variables */

mybox2.width = 3;

mybox2.height = 6;

mybox2.depth = 9;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol);

} }

16

17 of 79

Adding a Method That Takes Parameters

Here is a method that returns the square of the number 10:

int square()

{

return 10 * 10;

}

While this method does, indeed, return the value of 10 squared, its use

is very limited.

However, if you modify the method so that it takes a parameter, as shown next, then you can make square( ) much more useful.

int square(int i)

{

return i * i;

}

17

18 of 79

square( ) will return the square of whatever value it is called with. That is, square( ) is

now a general-purpose method that can compute the square of any integer value, rather than

just 10.

Here is an example:

int x, y;

x = square(5); // x equals 25

x = square(9); // x equals 81

y = 2;

x = square(y); // x equals 4

18

19 of 79

This program uses a parameterized method.

class Box {

double width;

double height;

double depth;

// compute and return volume

double volume() {

return width * height * depth;

}

// sets dimensions of box

void setDim(double w, double h, double d) {

width = w;

height = h;

depth = d;

}

}

19

20 of 79

​

​

class BoxDemo5 {

public static void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// initialize each box

mybox1.setDim(10, 20, 15);

mybox2.setDim(3, 6, 9);

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol);

}

}

20

21 of 79

Constructors

  • A constructor initializes an object immediately upon creation.
  • It has the same name as the class in which it resides and is syntactically similar to a method.
  • Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes.
  • Constructors look a little strange because they have no return type, not even void.
  • This is because the implicit return type of a class’ constructor is the class type itself.

Types of Constructors

1.Non Parameterized Constructor

2.Parameterized Constructor

21

22 of 79

Non parameterized Constructor:

class Box {

double width;

double height;

double depth;

Box()

{

System.out.println(“Constructor Box”);

width=10;

height=15;

depth=20;

}

​

​

23 of 79

// compute and return volume

double volume( ) {

return width * height * depth;

}

}

class BoxDemo4 {

public static void main(String args[]) {

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol);

}

}

​

​

24 of 79

Parameterized Constructors

/* Here, Box uses a parameterized constructor to

initialize the dimensions of a box.

*/

class Box {

double width;

double height;

double depth;

// This is the constructor for Box.

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

}

24

25 of 79

// compute and return volume

double volume() {

return width * height * depth;

}

}

class BoxDemo7 {

public static void main(String args[]) {

// declare, allocate, and initialize Box objects

Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box(3, 6, 9);

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol); } }

25

26 of 79

The this Keyword

  • Java defines the this keyword. this can be used inside any method to refer to the current object.
  • That is, this is always a reference to the object on which the method was invoked.
  • You can use this anywhere a reference to an object of the current class’ type is permitted
  • // A redundant use of this.

Eg:Box(double w, double h, double d) {

this.width = w;

this.height = h;

this.depth = d;

}

26

27 of 79

​

​

​

​

​

​

Usage of java this keyword

Here is given the 6 usage of java this keyword.

  • this can be used to refer current class instance variable.
  • this can be used to invoke current class method (implicitly)
  • this() can be used to invoke current class constructor.
  • this can be passed as an argument in the method call.
  • this can be passed as argument in the constructor call.
  • this can be used to return the current class instance from the method.

​

27

28 of 79

This : used to refer current instance variable

class Student {

String name;

Student(String name)

{

this.name = name; // 'this.name' refers to the field, 'name' is the parameter

}

}

28

29 of 79

Invoke Current Class Method (Explicitly)

class Greeter

{

void sayHello()

{

System.out.println("Hello!");

}

void triggerGreeting()

{ this.sayHello(); // Invoking current class method

}

}

29

30 of 79

Invoke Current Class Constructor (this())

class Rectangle

{

Rectangle()

{

this(10, 20); // Calls the parameterized constructor

}

Rectangle(int width, int height)

{

System.out.println("Width: " + width + ", Height: " + height);

}

}

30

31 of 79

Pass as an Argument in a Method Call

class Logger

{

void log(Document doc)

{

System.out.println("Logging document...");

}

}

class Document

{

void save()

{

Logger logger = new Logger();

logger.log(this); // Passing current object instance

} }

31

32 of 79

Pass as an Argument in a Constructor Call

class Engine

{

Car car;

Engine(Car car)

{ this.car = car; }

}

class Car

{ void start()

{ Engine engine = new Engine(this);

// Passing current object to Engine constructor } }

32

33 of 79

Return Current Class Instance from a Method

class Calculator

{

int value = 0;

Calculator add(int num)

{

this.value += num;

return this; // Returns the current instance

}

}

33

34 of 79

class Student{  

int rollno;  

String name;  

float fee;  

Student(int rollno,String name,float fee){  

rollno=rollno;  

name=name;  

fee=fee;  

}  

void display(){System.out.println(rollno+" "+name+" "+fee);}  

}  

class TestThis1{  

public static void main(String args[]){  

Student s1=new Student(111,"ankit",5000f);  

Student s2=new Student(112,"sumit",6000f);  

s1.display();  

s2.display();  

}}  

34

35 of 79

���Solution of the above problem by this keyword�

class Student{  

int rollno;  

String name;  

float fee;  

Student(int rollno,String name,float fee){  

this.rollno=rollno;  

this.name=name;  

this.fee=fee;  

}  

void display(){System.out.println(rollno+" "+name+" "+fee);}  

}    

class TestThis2{  

public static void main(String args[]){  

Student s1=new Student(111,"ankit",5000f);  

Student s2=new Student(112,"sumit",6000f);  

s1.display();  

s2.display();  

}}  

�

​

35

36 of 79

Program where this keyword is not required

class Student{  

int rollno;  

String name;  

float fee;  

Student(int r,String n,float f){  

rollno=r;  

name=n;  

fee=f;  

}  

void display(){System.out.println(rollno+" "+name+" "+fee);}  

}    

class TestThis3{  

public static void main(String args[]){  

Student s1=new Student(111,"ankit",5000f);  

Student s2=new Student(112,"sumit",6000f);  

s1.display();  

s2.display();  

}}  

​

36

37 of 79

Java Garbage Collection�

  • In java, garbage means unreferenced objects.
  • It is a way to destroy the unused objects.
  • To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

​

Advantage of Garbage Collection

  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

​

37

38 of 79

How can an object be unreferenced?

There are many ways:

  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object etc.

1) By nulling a reference:

  • Employee e=new Employee();  
  • e=null;  

2) By assigning a reference to another:

  • Employee e1=new Employee();  
  • Employee e2=new Employee();  
  • e1=e2;//now the first object referred by e1 is available for garbage
  •  collection  

3) By anonymous object:

  • new Employee(); 

​

38

39 of 79

finalize() method�

The finalize() method is called by the Garbage Collector just before an object is removed from memory.

It allows us to perform clean up activity.

Once the finalize() method completes, Garbage Collector destroys that object .finalize method is present in the Object class.

protected void finalize(){ }  

Finalize method is depricated due to various reasons like unpredictability

​

39

40 of 79

A Closer Look at Methods and Classes

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 the case, the methods are said to be overloaded, and the process is referred to as method overloading.
  • Method overloading is one of the ways that Java supports polymorphism.
  • 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.
  • Thus, overloaded methods must differ in the type and/or number of their parameters.

40

41 of 79

41

42 of 79

// Demonstrate method overloading.

class OverloadDemo {

void test() {

System.out.println("No parameters");

}

// Overload test for one integer parameter.

void test(int a) {

System.out.println("a: " + a);

}

// Overload test for two integer parameters.

void test(int a, int b) {

System.out.println("a and b: " + a + " " + b);

}

// overload test for a double parameter

double test(double a) {

System.out.println("double a: " + a);

return a*a;

}

}

42

43 of 79

class Overload {

public static void main(String args[]) {

OverloadDemo ob = new OverloadDemo();

double result;

// call all versions of test()

ob.test();

ob.test(10);

ob.test(10, 20);

result = ob.test(123.25);

System.out.println("Result of ob.test(123.25): " + result);

}

}

​

//Methods are overloaded

43

44 of 79

Overloading Constructors

/* Here, Box defines three constructors to initialize

the dimensions of a box various ways.

*/

class Box {

double width;

double height;

double depth;

// constructor used when all dimensions specified

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

}

44

45 of 79

// constructor used when no dimensions specified

Box() {

width = -1; // use -1 to indicate

height = -1; // an uninitialized

depth = -1; // box

}

// constructor used when cube is created

Box(double len) {

width = height = depth = len;

}

// compute and return volume

double volume() {

return width * height * depth;

}

}

45

46 of 79

class OverloadCons {

public static void main(String args[]) {

// create boxes using the various constructors

Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box();

Box mycube = new Box(7);

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

// get volume of cube

vol = mycube.volume();

System.out.println("Volume of mycube is " + vol);

}

}

​

46

47 of 79

Using Objects as Parameters

// Objects may be passed to methods.

class Test {

int a, b;

Test(int i, int j) {

a = i;

b = j;

}

// return true if o is equal to the invoking object

boolean equals(Test o) {

if(o.a == a && o.b == b) return true;

else return false;

}

}

47

48 of 79

class PassOb {

public static void main(String args[]) {

Test ob1 = new Test(100, 22);

Test ob2 = new Test(100, 22);

Test ob3 = new Test(-1, -1);

System.out.println("ob1 == ob2: " + ob1.equals(ob2));

System.out.println("ob1 == ob3: " + ob1.equals(ob3));

}

}

48

49 of 79

Question 1: E-Commerce Discount Calculator

Problem Statement: Design a class to calculate the final price of a product during checkout. The class must handle different types of discount applications using method overloading.

  • Class Name: OrderCheckout
  • Data Members:
    • double basePrice (The original price of the item)
    • double taxRate (The standard tax percentage applied, e.g., 5.0 for 5%)
  • Overloaded Methods: calculateFinalPrice
    1. calculateFinalPrice(): Returns the price with only the standard taxRate applied. (Formula: basePrice + (basePrice * taxRate / 100))
    2. calculateFinalPrice(double flatDiscount):

Subtracts the flatDiscount from the basePrice before applying the tax.

    • calculateFinalPrice(String couponCode): If the code is "FESTIVAL50", applies a 50% discount to the base price before tax. Otherwise, applies no discount.
    • calculateFinalPrice(int quantity, double bulkDiscountPercent): Multiplies the base price by quantity, applies the bulkDiscountPercent, and then adds the tax on the total.

​

49

50 of 79

  • Question 2: Smart Media Player
  • Problem Statement: Design a simulation of a smart media player that can play files based on various inputs, demonstrating how parameter order and types resolve overloaded method calls.
  • Class Name: MediaPlayer
  • Data Members:
    • String deviceName
    • int currentVolume (range 0 to 100)
    • boolean isMuted
  • Overloaded Methods: playAudio
    • playAudio(String fileName): Prints a message indicating the file is playing at the currentVolume.
    • playAudio(String fileName, int volumeLevel): Temporarily sets the player's volume to volumeLevel, then prints the playing message.
    • playAudio(int trackNumber, String playlistName): Fetches a track by its number from a specific playlist. (Print: "Playing track X from playlist Y").
    • playAudio(String podcastName, double playbackSpeed): Plays a podcast at the specified speed (e.g., 1.25x or 1.5x) at the default volume.

​

50

51 of 79

A Closer Look at Argument Passing

  • There are two ways that a computer language can pass an argument to a subroutine.
  • The first way is call-by-value.

This approach copies the value of an argument into the formal

parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument.

  • The second way an argument can be passed is call-by-reference.
  • In this approach, a reference to an argument (not the value of the argument) is passed to the parameter.
  • Inside the subroutine, this reference is used to access the actual argument specified in the call.
  • This means that changes made to the parameter will affect the argument used to call the subroutine.

51

52 of 79

// Primitive types are passed by value.

class Test {

void meth(int i, int j) {

i *= 2;

j /= 2;

}

}

class CallByValue {

public static void main(String args[]) {

Test ob = new Test();

int a = 15, b = 20;

System.out.println("a and b before call: " +a + " " + b);

ob.meth(a, b);

System.out.println("a and b after call: " +a + " " + b);

}

}

52

53 of 79

// Objects are passed by reference.

class Test {

int a, b;

Test(int i, int j) {

a = i;

b = j;

}

// pass an object

void meth(Test o) {

o.a *= 2;

o.b /= 2;

}

}

class CallByRef {

public static void main(String args[]) {

Test ob = new Test(15, 20);

System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);

ob.meth(ob);

System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);

}

}

53

54 of 79

Returning Objects

A method can return any type of data, including class types that you create.

For example, in the following program, the incrByTen( ) method returns an object in which the value of a is ten greater than it is in the invoking object.

// Returning an object.

class Test {

int a;

Test(int i) {

a = i;

}

Test incrByTen() {

Test temp = new Test(a+10);

return temp;

}

}

54

55 of 79

class RetOb {

public static void main(String args[]) {

Test ob1 = new Test(2);

Test ob2;

ob2 = ob1.incrByTen();

System.out.println("ob1.a: " + ob1.a);

System.out.println("ob2.a: " + ob2.a);

ob2 = ob2.incrByTen();

System.out.println("ob2.a after second increase: “ + ob2.a);

}

}

class Test {

int a;

Test(int i) {

a = i;

}

Test incrByTen() {

Test temp = new Test(a+10);

return temp;

}

}

55

56 of 79

Recursion

  • Java supports recursion. Recursion is the process of defining something in terms of itself.
  • Recursion is the attribute that allows a method to call itself.

​

  • A method that calls itself is said to be recursive.

56

57 of 79

// A simple example of recursion.

class Factorial {

// this is a recursive method

int fact(int n) {

int result;

if(n==1) return 1;

result = fact(n-1) * n;

return result;

}

class Recursion {

public static void main(String args[]) {

Factorial f = new Factorial();

System.out.println("Factorial of 3 is " + f.fact(3));

System.out.println("Factorial of 4 is " + f.fact(4));

System.out.println("Factorial of 5 is " + f.fact(5));

}

}

​

57

58 of 79

Introducing Access Control

  • Java’s access specifiers are public, private, and protected.
  • Java also defines a default access level.
  • Protected applies only when inheritance is involved.

​

​

/* This program demonstrates the difference between public and private. */

class Test {

int a; // default access

public int b; // public access

private int c; // private access

// methods to access c

void setc(int i) { // set c's value

c = i;

}

​

58

59 of 79

int getc() { // get c's value

return c;

}

}

class AccessTest {

public static void main(String args[]) {

Test ob = new Test();

// These are OK, a and b may be accessed directly

ob.a = 10;

ob.b = 20;

// This is not OK and will cause an error

// ob.c = 100; // Error!

// You must access c through its methods

ob.setc(100); // OK

System.out.println("a, b, and c: " + ob.a + " " +

ob.b + " " + ob.getc());

} }

59

60 of 79

Understanding static

  • It is possible to create a member that can be used by itself, without reference to a specific instance.
  • To create such a member, precede its declaration with the keyword static.
  • The static keyword in Java is used for memory management mainly.
  • When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.
  • The static can be:
  • Variable (also known as a class variable)
  • Method (also known as a class method)
  • Block
  • Nested class
  • The most common example of a static member is main( ).
  • main( ) is declared as static because it must be called before any objects exist.

​

60

61 of 79

  • Instance variables declared as static are, essentially, global variables.
  • When objects of its class are declared, no copy of a static variable is made.
  • Instead, all instances of the class share the same static variable.
  • Methods declared as static have several restrictions:
      • They can only call other static methods.
      • They must only access static data.
      • They cannot refer to this or super in any way

61

62 of 79

  • Outside of the class in which they are defined, static methods and variables can be used independently of any object.
  • To do so, you need only specify the name of their class followed

by the dot operator.

  • For example, if you wish to call a static method from outside its class, you can do so using the following general form:

classname.method( )

​

  • Here, classname is the name of the class in which the static method is declared.
  • A static variable can be accessed in the same way—by use of the dot operator on the name of the class.
  • Here is an example. Inside main( ), the static method callme( ) and the static variable b are accessed through their class name StaticDemo

62

63 of 79

Static Data Member

  • 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.
  • The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

  • It makes your program memory efficient (i.e., it saves memory).

Example of static variable

//Java Program to demonstrate the use of static variable  

class Student{  

   int rollno;//instance variable  

   String name;  

   static String college ="ITS";//static variable  

   //constructor  

   Student(int r, String n){  

   rollno = r;  

   name = n;  

   }  

   //method to display the values  

   void display (){System.out.println(rollno+" "+name+" "+college);}  

}  

�

63

64 of 79

//Test class to show the values of objects  

public class TestStaticVariable1{  

 public static void main(String args[]){  

 Student s1 = new Student(111,"Karan");  

 Student s2 = new Student(222,"Aryan");  

 //we can change the college of all objects by the single line of code  

 //Student.college="BBDIT";  

 s1.display();  

 s2.display();  

 }  

}  

​

64

65 of 79

Java static method�

If you apply static keyword with any method, it is known as static method.

  • 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.

Example of static method

//Java Program to demonstrate the use of a static method.  

class Student{  

     int rollno;  

     String name;  

     static String college = "ITS";  

     

65

66 of 79

//static method to change the value of static variable  

     static void change(){  

     college = "BBDIT";  

     }  

     //constructor to initialize the variable  

     Student(int r, String n){  

     rollno = r;  

     name = n;  

     }  

     //method to display values  

     void display(){System.out.println(rollno+" "+name+" "+college);}  

}  

//Test class to create and display the values of object  

public class TestStaticMethod{  

    public static void main(String args[]){  

    Student.change();//calling change method  

    //creating objects  

    Student s1 = new Student(111,"Karan");  

    Student s2 = new Student(222,"Aryan");  

    Student s3 = new Student(333,"Sonoo");  

    //calling display method  

    s1.display();  

    s2.display();  

    s3.display();  

    }  

}  

​

​

66

67 of 79

  •  Java static block
  • Is used to initialize the static data member.
  • It is executed before the main method at the time of classloading.

Example of static block

class A2{  

  static{System.out.println("static block is invoked");}  

  public static void main(String args[]){  

   System.out.println("Hello main");  

  }  

}  

Output:

static block is invoked

Hello main

�

67

68 of 79

Introducing final

  • The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
  • variable
  • method
  • class
  • The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only.
  • The blank final variable can be static also which will be initialized in the static block only. 

​

68

69 of 79

  • A variable can be declared as final.
  • Doing so prevents its contents from being modified.
  • This means that you must initialize a final variable when it is declared.
  • For example:
  • final int FILE_NEW = 1;
  • final int FILE_OPEN = 2;
  • final int FILE_SAVE = 3;
  • final int FILE_SAVEAS = 4;
  • final int FILE_QUIT = 5;
  • It is a common coding convention to choose all uppercase identifiers for final variables.
  • Variables declared as final do not occupy memory on a per-instance basis.
  • Thus, a final variable is essentially a constant.
  • The keyword final can also be applied to methods, but its meaning is substantially different than when it is applied to variables

69

70 of 79

class Bike9{  

 final int speedlimit=90;//final variable  

 void run(){  

  speedlimit=400;  

 }  

 public static void main(String args[]){  

 Bike9 obj=new  Bike9();  

 obj.run();  

 }  

}//end of class

​

70

71 of 79

2) Java final method

If you make any method as final, you cannot override it.

Example of final method

class Bike{  

  final void run(){System.out.println("running");}  

}  

     

class Honda extends Bike{  

   void run(){System.out.println("running safely with 100kmph");}  

     

   public static void main(String args[]){  

   Honda honda= new Honda();  

   honda.run();  

   }  

}  

Test it NowOutput:Compile Time Error

​

71

72 of 79

3)Java final class

If you make any class as final, you cannot extend it.

Example of final class

final class Bike{}  

  

class Honda1 extends Bike{  

  void run(){System.out.println("running safely with 100kmph");}  

    

  public static void main(String args[]){  

  Honda1 honda= new Honda1();  

  honda.run();  

  }  

}  

​

72

73 of 79

Arrays Revisited

  • Now that you know about classes, an important point can be made about arrays: they are implemented as objects.
  • Because of this, there is a special array attribute that you will want to take advantage of. Specifically, the size of an array—that is, the number of elements that an array can hold—is found in its length instance variable.
  • All arrays have this variable, and it will always hold the size of the array.
  • Here is a program that demonstrates this property:

73

74 of 79

// This program demonstrates the length array member.

class Length {

public static void main(String args[]) {

int a1[] = new int[10];

int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};

int a3[] = {4, 3, 2, 1};

System.out.println("length of a1 is " + a1.length);

System.out.println("length of a2 is " + a2.length);

System.out.println("length of a3 is " + a3.length);

}

}

74

75 of 79

Introducing Nested and Inner Classes

  • It is possible to define a class within another class; such classes are known as nested classes.
  • The scope of a nested class is bounded by the scope of its enclosing class.
  • If class B is defined within class A, then B does not exist independently of A.
  • A nested class has access to the members, including private members, of the class in which it is nested.

75

76 of 79

  • There are two types of nested classes: static and non-static.
  • A static nested class is one that has the static modifier applied. Because it is static, it must access the non-static members of its enclosing class through an object.
  • That is, it cannot refer to non-static members of its enclosing class directly.
  • Because of this restriction, static nested classes are seldom used.
  • The most important type of nested class is the inner class.
  • An inner class is a non-static nested class.
  • It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do.

76

77 of 79

class Outer {

int outer_x = 100;

void test() {

Inner inner = new Inner();

inner.display();

}

// this is an inner class

class Inner {

void display() {

System.out.println("display: outer_x = " + outer_x);

}

}

}

class InnerClassDemo {

public static void main(String args[]) {

Outer outer = new Outer();

outer.test();

}

}

77

78 of 79

// This program will not compile.

class Outer {

int outer_x = 100;

void test() {

Inner inner = new Inner();

inner.display();

}

// this is an inner class

class Inner {

int y = 10; // y is local to Inner

void display() {

System.out.println("display: outer_x = " + outer_x);

}

}

void showy() {

System.out.println(y);

}

}

class InnerClassDemo {

public static void main(String args[]) {

Outer outer = new Outer();

outer.test();

}

}

78

79 of 79

// Define an inner class within a for loop.

class Outer {

int outer_x = 100;

void test() {

for(int i=0; i<10; i++) {

class Inner {

void display() {

System.out.println("display: outer_x = " + outer_x);

}

}

Inner inner = new Inner();

inner.display();

}

}

}

class InnerClassDemo {

public static void main(String args[])

{

Outer outer = new Outer();

outer.test();

}

}

​

79