1 of 39

You must know

  • For any computer program the core elements are:
    • (1) data (2) functions.

The way of programming can be divided into 2 categories:

1. Structural/Procedural languages

2. object oriented languages

  1. Data encapsulation
  2. Data abstraction
  3. Polymorphism
  4. Inheritance

2 of 39

You must know

Object word is taken from the real world examples….

Class can be considered as a blueprint for various objects.

  • Structural/procedural programming views these 2 core elements as two separate entities, whereas object-oriented programming views them as single entity. This mechanism of wrapping data and method into a single unit is known as encapsulation.
  • Data abstraction is a process of representing the essential features of the objects without including implementation detail. Abstraction is a concept that hides the complexity.
  • Polymorphism means ‘many forms’.
  • Polymorphism contains 2 things: method overloading and operator overloading.

3 of 39

Ch-8

Classes and Objects in Java

4 of 39

Class and object

  • A class contains both data and(attributes) and program code(methods).
  • Each and every java program contains at least one class containing main function inside it.
  • The program execution starts from the class where the main function is available.
  • When the class is executed, the main method is called.

5 of 39

Understanding an example

  • Let us understand the concept of class and object through an example of Room.
  • A room of a house, hostel, hotel or school possess some common characteristic like length, height, width, number of windows, number of doors and direction.
  • We can write a java program to create a class named Room and can create objects like r1, r2 related to Room class for various rooms like hotel room, class room.
  • Four attributes: length,width,height and nWindows and three methods : setAttr(), area(), display() are there.
  • setAttr() sets the value of all four attributes for a room, area() method calculates the area of a room and display method shows values of attributes.

6 of 39

class Room

length, width, height, nWindows

setAttr(), area(), display()

class RoomDemo

Contains main() function

Contains objects:r1 and r2

Program name : RoomDemo.java

7 of 39

Class Room

{

float length, width, height;

byte nWindows;

void setAttr(float l, float w, float h, byte n)

{

length = l;width = w;height = h;

nWindows = n;

}

double area()

{ return (length * width); }

void display()

{

System.out.println(“\n Length : “ + length);

System.out.println(“\n Width : “ + width);

System.out.println(“\n Height : “ + height);

System.out.println(“\n Number of windows : “ + nWindows);

}

}

8 of 39

class RoomDemo

{

public static void main(String args[])

{

Room r1;

r1 = new Room();

Room r2 = new Room();

r1.display();

r2.display();

r1.setAttr(18, 12.5f, 10, (byte)2);

r2.setAttr(14, 11, 10, (byte)1);

r1.display();

r2.display();

System.out.println(“\n Area of r1 is : “ + r1.area());

System.out.println(“\n Area of r2 is : “ + r2.area());

}

}

9 of 39

Understanding program

  • The program contains 2 classes: Room and RoomDemo.
  • main function is in RoomDemo class so execution starts from RoomDemo class.
  • r1 and r2 are objects of Room class. Both the objects contain 4 attributes: length, width, height and nWindows and �3 methods: setAttr(), area() and display().
  • Room r1; declares an object named r1 of Room class.
    • Declaring a variable does not create an object.
    • No variable can ever store an object. A variable declared using class type can only store a reference to an object. So variable of class type is also referred to as reference variable.
  • r1 = new Room(); creates an object.
    • new operator is used to create an object.
    • There is a special portion of memory called heap where the object is stored.

10 of 39

Classification of Variables

  • Variables declared in a class are of three types:
    • Local Variables
    • Instance Variables
    • Class Variables

11 of 39

Local Variables

  • Variables defined inside methods or blocks are called local variables.
  • For eg.� {�
  • float length;� }
  • System.out.println(length); // This statement shows error
  • Local variables are created when the method or block is started and gets destroyed when the method or block as completed.

Local Variable

12 of 39

Instance Variables

  • Instance variables are variables defined within a class but outside any method.
  • For eg.� class Room� {� float length;� void setAttr(length l, width h)� {� int a;� }� }

Instance variable

Local Variable

13 of 39

ClassVariables

  • Class variables are variables defined with in a class, outside any method, with static keyword.
  • These variables are allocated memory only once per class and is shared by all its objects.
  • For eg.� class Room� {� static float totWindows;� float length;� void setAttr(length l, width h)� {� int a;� }� }

Instance variable

Local Variable

Class variable

14 of 39

Polymorphism

  • Polymorphism means many forms.
  • In Java we can have different methods that have the same name but a different signature.
  • This is also known as method overloading.
  • For eg.� static int max(int x, int y){….}� static int max(int x, int y, int z) {…}� static double max(double x, double y, double z) {…}

  • These are the methods created in a single class, with the same name but having different signatures.

15 of 39

Polymorphism

Class printLine

{

static void printline()

{

for(int i=0;i<=40;i++)

System.out.print(‘=‘);

System.out.println();

}

static void printline(int n)

{

for(int i=0;i<=n;i++)

System.out.print(‘#’);

System.out.println();

}

Methods with the same name

Havin g different signature.

Method overloading

16 of 39

Constructor

  • Constructor is a special kind of method that is invoked when a new object is created.
  • The main purpose of constructor is to perform initializing actions.
  • Each and every class contains its default constructor.
    • Constructor must have the same name as class name. For eg. Room()
    • Constructor does not have return type.
    • Constructor is invoked implicitly only when an object is constructed using new operator. For eg. r1 = new Room()

  • Like other methods constructor can also be overloaded, that is known as user defined constructor.

Default constructor

17 of 39

Constructor Overloading

  • Like other methods, constructor can also be overloaded.
  • It can be done by varying list of parameters.

For eg.

class Room

{

float length, width,height;

Room(float l, float w, float h)

{

length = l;width = w;height=h;

}

Room(float l, float w)

{

length=l;width=w;

}

Constructor overloading with

Different signatures.

18 of 39

User defined constructor

  • In presence of user-defined constructor in a class, default constructor is no more available.
  • In presence of User-defined constructor an attempt to create an object using constructor without arguments returns to an error.
  • To solve this we need to provide a user defined no argument constructor.

class Room

{

float length, width,height;

Room();

Room(float l, float w, float h)

{

length = l;width = w;height=h;

}

Room(float l, float w)

{

length=l;width=w;

}

19 of 39

Visibility Modifier

  • It is also known as access modifier.
  • Visibility modifiers are of four type:
    • public, package, protected and private
  • When no modifier is used, java uses default visibility ie. package.

Access Modifier public package protected private

Visibility widest 🡪 🡪 🡪 🡪 🡪 narrowest

20 of 39

public

  • It is the widest possible visibility for any variable or method.
  • If we want to make it visible to all the classes outside this class, declare the method or variable to have public access.
  • For eg.
    • Public float length
    • Public double area()
  • public keyword is also used with main() method to make it available to everyone. Ie. public static void main()

21 of 39

package

  • This is the next level of access that has no precise name.
  • It is indicated by the lack of any access modifier keyword in a declaration.
  • This is the default level of protection.
  • Its scope is narrower than public
  • The variable or method declared as package can be accessed from anywhere in the package that contains the class.
  • Till now we have used package visibility in our programs for creating methods like setAttr(), display(), etc.

22 of 39

protected

  • This level of protection has wider visibility than private but narrower than public or package.
  • This level of protection is used to allow the access only to subclasses or to share with the methods declared as friend.
  • For eg.
    • protected float nWindows;

23 of 39

private

  • This is the highest level of protection.
  • It has the narrowest visibility.
  • The private methods and variables are directly accessible only by the methods defined within a class.
  • They cannot be seen by any other class.
  • It provides data encapsulation technique.

24 of 39

class Rectangle

{

private double length, width;

{

Rectangle(double x, double y)

{

length =x; width = y;

}

Rectangle(){};

double area() {return length * width;}

void display()

{System.out.println(“Rectangle with length=“+length + “width” +width);}

}

Class RectangleVisibility1

{

public static void main(String[] s)

{ Rectangle rect1;

rect1 = new Rectangle();

Rectangle rect2 = new Rectangle(10,15);

rect1.display();rect2.display();

System.out.println(“Area of rectangle with length” +rect2.length+”width”+ � rect2.width + “is” + rect2.area());

}

}

Length & width can’t be accessed

due to private.

25 of 39

class Rectangle

{

private double length, width;

{

Rectangle(double x, double y)

{

length =x; width = y;

}

Rectangle(){};

double area() {return length * width;}

void display()

{System.out.println(“Rectangle with length=“+length + “width” +width);}

double getlength(){return length;} double getwidth() {return witdh;}

}

Class RectangleVisibility1

{

public static void main(String[] s)

{ Rectangle rect1;

rect1 = new Rectangle();

Rectangle rect2 = new Rectangle(10,15);

rect1.display();rect2.display();

System.out.println(“Area of rectangle with length” +rect2.getlength()+”width”+ rect2.getwidth() + “is” + rect2.area());

}

}

26 of 39

Accessor and Mutator Methods

  • When we restrict access to data by declaring them as private, our purpose is to protect them from getting directly accessed or midified by methods of other class.
  • If we want to allow such data to be used by others, then we write accessor methods.
  • Similarly If we want to allow such data to be modified by others then we write mutator methods.
  • Conventionally, naming of accessor and mutator methods is to capitalize the first letter of variable name and then prepend the variable name with the prefixes get or set respectively.
    • For eg. void getLength(){return length;}� void setLength(float l) {length=l;}

27 of 39

Inheritance

  • Inheritance provides “is a” relationship between two class.
  • Inheritance allows us to build new class with added capabilities by extending existing class.
  • A person inherits the characteristics of parents, similarly a child class automatically inherits the attributes and methods of its parent class.
  • Parent class is also referred to as superclass or base class.
  • Child class is also referred to as subclass , derived class or extended class.
  • Remember that common features are kept in superclass.
  • Although subclass contains its own attributes and methods, it automatically inherits the attributes and methods of superclass.
  • In short classroom is a room. Similarly a student is a person.
  • So room can be considered as superclass containing length, width like attributes and area, display like methods.
  • Classroom inherits all the attributes of room and it also contains additional attributes like number of benches and seats per bench.

28 of 39

Inheritance

Room

Length:float

Width:float

Height:float

nWindows:byte

Room()

Room(float l, float w, float h, byte n)

Room(float l, float w)

Void display()

Classroom

nBenches:int

nSeatsBench:int

Classroom()

Classroom(float l, float w, float h, byte n, int nB, int nSB)

Void show()

Void display()

Int getSeats()

Super class or Parent class

sub class or child class

29 of 39

Inheritance

  • Extends keyword is used to create a subclass in Java.
    • For eg. class Classroom extends Room

Where Room is super class and Classroom is its subclass.

Any method or variable available in superclass can be used from its subclass by following statement.

For eg. To call display method of a superclass we can use the statement.

super.display();

30 of 39

31 of 39

32 of 39

33 of 39

How many types of variables are there in Java?

3

Variables defined inside methods or blocks are called _______

Local Variables

Which type of variables contain highest availability scope?

Class variables

34 of 39

__________ variables are variables defined within a class but outside any method.

Instance variables

Which variables are allocated memory only once per class and is shared by all its objects.

Class Variables

___________ means many forms.

Polymorphism

35 of 39

_________ is a special kind of method that is invoked when a new object is created.

Constructor

What is the main purpose of constructor?

To perform initializing actions

Each and every class contains a constructor known as ________.

Default constructor

36 of 39

How many visibility modifiers are there?

4

Name all the visibility modifiers.

Public , package , protected and private

Each and every class contains a constructor known as ________.

Default constructor

37 of 39

Which constructor is not available in presence of user defined constructor?

Default Constructor

If we want to make a variable visible to all the classes outside this class, declare the method or variable __________

public

What is the visibility of main function?

public

38 of 39

_________ is indicated by the lack of any access modifier keyword in a declaration.

package

Which visibility provides data encapsulation technique.

private

Which level of protection has wider visibility than private but narrower than public or package.

protected

39 of 39

Which level of protection is used to allow the access only to subclasses or to share with the methods declared as friend.

protected

Which is the default level of protection.

package

Which level of protection has wider visibility than private but narrower than public or package.

protected