You are on page 1of 33

OOP WITH JAVA 15CS42T 2020-21

UNIT-2

CLASSES, OBJECTS AND METHODS

Defining a class :

Class is a user defined data type; it consists of variables and methods. These variables are

termed as instances of classes, which are the actual objects.

Class <class name> [extends superclassname]

[Variables or fields declaration;]

[Methods Declaration;]

Everything inside the square bracket is optional, so we can create an empty class also.

Fields Declaration :–

A variable can be placed within a class. A class supports any number of variables within it.

Example:-

class rectangle

Int length;

Int width;

The “rectangle” contains two integer type instance variable.

COMPUTER SCIENCE & ENGINEERING age 1


OOP WITH JAVA 15CS42T 2020-21

Methods of declaration :-

A class with only data fields and without methods has no life. Therefore it is necessary to add

methods in a class for manipulating data contained in the class.

Methods are declared inside the body of the class immediately after the declaration of

variables.

The general form is

return_type method_name(list of parameters)

Body of the method

The method declarations have 4 basic parts :

The name of the method

The type of values the method returns

List of parameters with its data type

Body of the method

Example:-

class rect

Int l,w;

Void getdata (int x,int y);

l=x;

COMPUTER SCIENCE & ENGINEERING age 2


OOP WITH JAVA 15CS42T 2020-21

w=y;

Int rectangle()

int area;

area=l*w;

return(area);

Creating objects :

In java, the “new” operators are used to create object. There are two ways to create object.

The General syntax is

Classname object_name=new classname

1. Rectangle obj;

obj=new Rectangle ();

2. Rectangle obj=new Rectangle();

Accessing class Members :

The variables and methods of a class cannot be accessed directly outside the class. For this,

an object of that class & dot (.) operator are used to access the members of the class.

The General Syntax is

Object Name.variableName=value;

COMPUTER SCIENCE & ENGINEERING age 3


OOP WITH JAVA 15CS42T 2020-21

objectName.methodName(parameter_list);

Example:-

Class rectangle

int l,w;

Void getdata (int x, int y);

l=x;

w=y;

Int rectarea()

int area=l*w;

return (area);

Class rect

Public static void main (String arg[])

int area1;

Rectangle obj=new Rectangle ();

obj.getdata(10,20);

area1=rectarea();

System.out.println(“Area=”+area1);

COMPUTER SCIENCE & ENGINEERING age 4


OOP WITH JAVA 15CS42T 2020-21

Constructors :

Java supports a special type of method called “Constructor” that enables an object to

initialize when it is created.

The constructor name should be same as class name. Java constructors does not specify any

return type not even void.

Example:-

Class Rectangle

int length, width;

Rectangle (intx , int y)

length=x;

width=y;

int rectarea()

return (length*width);

Class RectangleArea

{
COMPUTER SCIENCE & ENGINEERING age 5
OOP WITH JAVA 15CS42T 2020-21

Public static void main (String arg[])

Rectangle obj=new Rectangle (10, 15);

int area=rectArea();

System.out.println(“Area=”+area);

Method Overloading :

Java supports “Method overloading”. This is used when objects are required to perform

similar tasks but using different input parameters. When we call a method using an object, java

matches the method name first & then decides which one of the definitions to execute. This process

is known as “Polymorphism”.

Example -

Class Rectangle

int length, width;

Rectangle (intx )

length=width=x;

Rectangle (intx , int y)

length=x;

width=y;

COMPUTER SCIENCE & ENGINEERING age 6


OOP WITH JAVA 15CS42T 2020-21

Int rectarea()

int area=length*width;

return (area);

Class result

Public static void main(String arg[])

Rectangle r1= new Rectangle (50);

Rectangle r2=new Rectangle (10,20);

int a1=r1.rectarea ();

int a2=r2.rectarea ();

System.out.println(“Area=”+a1);

System.out.println(“Area=”+a2);

Static members :

The members that are detected using the static keyword are called “Static Members”. Since

these members are associated with class it rather than individual objects.

COMPUTER SCIENCE & ENGINEERING age 7


OOP WITH JAVA 15CS42T 2020-21

The static variables & static methods are without creating the object of the class. They are

invoked using the class name.

Example -

Class operation

Static int add (int x, int y)

Return(x+y);

Static int mul(int x, int y)

Return(x*y);

Class result

Public static void main (String arg[])

Int s=operation.add(10,20);

Int m=operation.mul (20, 10);

System.out.println(“Sum=”+s);

System.out.println(“Mul=”+m);

COMPUTER SCIENCE & ENGINEERING age 8


OOP WITH JAVA 15CS42T 2020-21

Nesting of method :

A method can be called by using only its name by another method of the same class. This is

known as “Nesting of method”.

Example:-

Class nesting

int m,n;

nesting (int x, int y);

m=x;

n=y;

int largest ()

If (m>=n)

return (m);

else

return (n);

void display ()

int large=largest ();

System.out.println(“Largest no=”+large);

COMPUTER SCIENCE & ENGINEERING age 9


OOP WITH JAVA 15CS42T 2020-21

Class nestingTest

Public static void main (String arg[])

nesting obj=new nesting (10, 20);

obj.display();

Inheritance extending a class :

“Creating a new class & reusing the properties of old class is called as inheritance”.

Here old class is called as “Base class” or “Parent class” or “Super class”. The new class

created is called as “Sub class” or “Derived class” or “Child class”.

“The inheritance allows subclass to inherit all the variables & method of the super class.

 The advantage of inheritance is “Reusability”.

The following are the different form or types of inheritance.

1. Single level inheritance: - One super class & only one sub class.

A
Super class

B
Sub class

COMPUTER SCIENCE & ENGINEERING age 10


OOP WITH JAVA 15CS42T 2020-21

2. Multiple Inheritances: - more than one super class & one sub class.

Super class
A B

Sub class

3. Hierarchical Inheritance: - one super class & many sub class super class.

Super class
A

B C
Sub class

4. Multi-Level Inheritance: - It is a derived from a derived class.

Defining a subclass :

The general form of subclass is follows

Class subclassname extends superclassname

COMPUTER SCIENCE & ENGINEERING age 11


OOP WITH JAVA 15CS42T 2020-21

Variable declaration

Method declaration

The keyword “Extends” signifies that the properties of the super class are extended to the

subclass.

The below program illustrate the single inheritances & “super” keywords.

Class Rectangle

int length, width;

Rectangle (int x, int y)

length=x;

width=y;

int area ()

int a=length*width;

return (a);

Class room extends Rectangle

Rectangle

int height;

COMPUTER SCIENCE & ENGINEERING age 12


OOP WITH JAVA 15CS42T 2020-21

room (int x, int y, int z)

super(x, y);

height=z;

int volumearea()

int a1=length*width*height;

return (a);

Class result

Public static void main (String arg[])

room r1=new room(10,20);

int a1=r1.area();

int a2=r2.volumearea()

System.out.println(“Area=”+a1);

System.out.println(“Volumearea=”+a2);

Here “Rectangle” is the super class & room is the subclass. Now room includes 3 variables

length, width & height & two method “area ()” & vloumearea().

The subclass constructor uses the keyword “Super” to call the super class constructor.

COMPUTER SCIENCE & ENGINEERING age 13


OOP WITH JAVA 15CS42T 2020-21

The keyword “super” is used under the following conditions.

 The first statement of the sub class constructor must use the keyword “Super” to call the

super class constructor.

 “Super” keyword must be used only in the “superclass” constructor.

 Super keyword should include the same number & type of parameters specified in super class

constructor.

Overriding methods :

The method defines in the subclass has the same name, same arguments & same return type

as a method in the super class. Then this method is called as “Overriding methods”.

The method defined in the sub class is invoked & executed instead of the one in the super

class.

Example:-

Class super

int x;

super(int a)

x=y;

Void display()

System.out.println(“Super x=” +x);

COMPUTER SCIENCE & ENGINEERING age 14


OOP WITH JAVA 15CS42T 2020-21

Class sub extends super

int y;

sub (int a, int b)

super (a);

y=b;

Void display()

System.out.println(“Super x=”+x);

System.out.println(“Super y=”+y);

Final variables & final methods :

All methods & variables can be overridden by default. To present overriding a method or

variables declare them as “Final” keyword in the super class.

Example:-

Final int size=100;

Final void showstatus()

....

.....

COMPUTER SCIENCE & ENGINEERING age 15


OOP WITH JAVA 15CS42T 2020-21

Final classes :

Some times to prevent a class being further sub classes for security reasons. A class that

cannot be subclass is called as “Final class”.

Example:-

final calss A

...

....

Finalize method :

Garbage collector automatically frees up memory resources used by the java objects. The

garbage collector cannot free the memory resources which are occupied by non object resources.

In order to clear up these resources java provide “finalizer()” method. This is similar to

destructor in c++ language.

Abstract methods & classes :

The “abstract” is a keyword. It can be used for both methods & classes. The abstract method

must always be redefined in a sub class thus making overriding compulsory.

When a class contains at least one “abstract method” then the class should be declared as

“abstract”.

Example:-

Abstract class a

COMPUTER SCIENCE & ENGINEERING age 16


OOP WITH JAVA 15CS42T 2020-21

....

.....

Abstract void display ()

.....

....

While using abstract classes. We must satisfy the following conditions.

 We cannot create the object for abstract class.

 The abstract methods of an abstract class must be redefined in its subclass.

 We cannot declare abstract constructor.

 We cannot declare static methods.

Example:-

Abstract class A

Abstract void show();

Class B extends A

Void show()

COMPUTER SCIENCE & ENGINEERING age 17


OOP WITH JAVA 15CS42T 2020-21

System.out.println (“inside B class”);

Class abstract demo

Public static void main(String arg[])

B obj=new B()

A.show();

Methods with variable arguments :

It represents variable length arguments in methods. It makes the java code simple & flexible.

The General Syntax is.

<access specifier> <static> void method_name(abstract......arguments)

......

.....

Example:-

Class examplearg

COMPUTER SCIENCE & ENGINEERING age 18


OOP WITH JAVA 15CS42T 2020-21

String str1;

examplearg(String varg[])

for(int i=0;i<vargs.length; i++)

str1=varg[i];

System.out.println(str1);

Public static void main (String arg[])

examplearg ex=new examplearg(args);

Visibility controls :

There are 3 types of visibility controls.

1. Public

2. Private

3. Protected.

1. Public: - the public members are visible to all classes & also outside the class.

When no access modifier is specified, that member is having the default or friendly access.

COMPUTER SCIENCE & ENGINEERING age 19


OOP WITH JAVA 15CS42T 2020-21

The friendly members are visible to all classes in the same package.

2. Private: - the private members are visible only within the class.

3. Protected: - the protected members are visible not only to same class. It is available to all sub

class in the same package.

4. Private Protected: - the private protected member’s visibility level to between “protected” &

private”. These are available to classes & sub class.

Access Public Protected Friendly Private Private

modifier protected

Access

locations

Same Class Yes Yes Yes Yes Yes

Sub class in Yes Yes Yes Yes No

same

package

Other classes Yes Yes Yes No No

in same

package

Subclass in Yes Yes No No No

other

package

Non subclass Yes No No No No

in other

COMPUTER SCIENCE & ENGINEERING age 20


OOP WITH JAVA 15CS42T 2020-21

package

String :

String is a sequence of character or collection character. In java, Strings are class objects and

implemented using two classes.

1. String

2. String Buffer

In java, String is not an array of character; it does not hold “Null” value at the end . String

may be declared & created by using “new” keyword as followed.

String name;

Name=new String(“Hello”); OR

String name=new String(“Hello”);

String Arrays

We can also create & use arrays that contain settings

String itemArray[]=new String[3]

It will create an “itemArray “of size 3 to hold 3 string constants.

String methods

1. s2=s1.toLowerCaseConverts the String “s1” to all lower case.

COMPUTER SCIENCE & ENGINEERING age 21


OOP WITH JAVA 15CS42T 2020-21

2. s2=s1.toUpperCaseConverts the Strings “s1” to all Upper case.

3. S2=s1.replace(‘x’,’y’)Replace all appearance of “x “with “y”.

4. s2=s1.trim()Remove white spaces at the beginning & end of the String s1.

5. s1.equals(s2)Returns “True” if s1 is equal to s2.

6. s1.equalIgnoreCase(s2)Returns “True” if s1=s2, ignoring the case of characters.

7. s1.length() Gives the length of s1.

8. s1.ChartAt(n)Returns the nth character of String s1.

Ex:- String s1= “Govt”; s1.ChartAt(3);

9. s1.compareTo(s2)Returns 0 if (s1=s2) positive no if s1>s2 negative no if s1<s2.

10.s1.concat(s2)concatenates s1 &s2 That is adding s2 string to end of string s1.

Write a java program to ordering of String

Class StringOrdering

String name[]={“rama”, “akash”, “chandru”, “Viru”};

Public static void main(String arg[])

Int size=name.length;

String temp=null;

COMPUTER SCIENCE & ENGINEERING age 22


OOP WITH JAVA 15CS42T 2020-21

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

for (int j=i+1; j<size; j++)

If(name[j].compareTo[i]<0)

Temp=name[i];

name[i]=name[j];

Name[j]=temp;

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

System.out.println (name[i]);

StringBuffer class

String class creates string with fixed-length. String Buffer class creates String with flexible

length that can be modified in terms of length & content.

StringBuffer methods -

1.s1.setChartAt(n, ‘x’) Modifies the nth Character to x.

COMPUTER SCIENCE & ENGINEERING age 23


OOP WITH JAVA 15CS42T 2020-21

2.s1.append(s2) Appends the string s2 to s1 at the end.

3.s1.insert(n,s2) Inserts the string s2 at the position n of the string s1.

4.s1.setLegth(n) Sets the length of String s1 to n. If n less then s1.length then s1 will be truncked.

If it is greater than 0 will be added.

Ex:- s1= “Government” s1= “Govt”

S1.setLength(3) s1=setLength(9)

S1=Gov s1= “Govt00000”

Vectors

Vector is a built-in class & contained in the “java.util” package. This class can be used to

create a generic dynamic array known as vector. It can hold any types of object & any numbers.

Vectors are created as follows

Vector intvect=New Vector(); - Declarting without size.

Vector list=new Vector(3) - declaring with size.

A vector without size can accommodate an unknown number of items.

Advantages

 It is convenient to use vectors to store objects.

 Vector can be used to store a list of objects that may vary in size.

 We can add & delete objects from the list as and when requested.

Vector methods

COMPUTER SCIENCE & ENGINEERING age 24


OOP WITH JAVA 15CS42T 2020-21

1.addElement() To add the item to the list.

2.elementAt() To obtain the element at specific location.

3.Size() To gives the number of objects present in list.

4.removeElement(item) Removes the specified item from the list.

5.removeAllelemnts() Removes all the elements in the list.

6.insertElementAt(item,n) Insert the item at nth position.

7. Copyinto (array) Copies all items from list to array.

Exmaple:-

Import java.util.*;

Class ExVector

Public static void main(String arg[])

Vector list=new Vector();

Int length=org.length;

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

List.addElement(arg[i]);

List.insertElement(“COBOL”,2);

int size=list.size();

String listArray[]=new String[size];

COMPUTER SCIENCE & ENGINEERING age 25


OOP WITH JAVA 15CS42T 2020-21

List.copyInto(listArray);

System.out.println(“list of Languages”);

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

System.out.println(listArray[i]);

Enumerated Types

Java supports “enumerated type” using “enum” keyword. This keyword is similar to

“Static final”.

It allows to enumerate contain one at a time over all elements in a collection of objects.

Advantages

1. Compile time type safety

2. We can use the enum keyword in switch statement

Example:-

Class workingdays

Enum days

Sunday,Monday,Tuesday,Wednesday,Thursday,Friday Saturday;

COMPUTER SCIENCE & ENGINEERING age 26


OOP WITH JAVA 15CS42T 2020-21

Public static void main()

For (days d; days.values)

Weekend(d);

Private static void weekend(days d)

If(d.equals(days.Sunday)

System.out.println(“value=”+d+”is a Holiday”);

Else

System.out.println(“Value=”+d+”is a Working day”);

Wrapper classes

For a many of the operations java does not supports primitive data types like int , float,

double etc.

A primitive data type has to be converted into object types using the wrapper classes.

Wrapper classes are present in “java.long package.

Each primitive data types contains corresponding wrapper classes type

COMPUTER SCIENCE & ENGINEERING age 27


OOP WITH JAVA 15CS42T 2020-21

Simple type wrapper class

int Integer

float Float

double Double

long Long

char Character

Boolean Boolean

The wrapper classes have number of methods to handling primitive data types & objects.

1. Converting primitive numbers to object numbers

a. int i; integer iob =new Integer(i)

Converts integer variable “i” into an object “iob”.

b. float f; float fob=new Float (f)

Converts float variable “f” into an object “fob”.

c. double d; Double dob=new Double(d);

Converts double variable “d” into an object “dob”.

d. long l; Long lob=new Long(l);

Converts long variable “l” into an object “lob”.

2. Converting object members to primitive numbers

a. int i=iob.intValue() Converts object “iob” to primitives variable “i”.

b. float f=fob.floatValues() Convert object “fob” to primitive variable “f”.

c. long l=lob.langValues() Convert object “lob” to primitive variable “l”.

COMPUTER SCIENCE & ENGINEERING age 28


OOP WITH JAVA 15CS42T 2020-21

d. double d=dob.doubleValues() Convert object “dob” to primitive variable “d”.

3. Converting numbers to Strings

a. int i; String str=Integer.toString(i)Converts integer variable “i” to String object “str”.

b. float f ; String str=Float.toString(i)Converts float variable “f” to String object “str”.

c. double d; String str=Double.toString(i)Converts double variable “d” to String object “str”.

d. long l; String str=Long.toString(i)Converts long variable “l” to String object “str”.

4. Converting String object to numeric objects

a.iob=Integer.ValueOf(str) converts String “Str” to Integer object “iob”.

b. fob=Float.ValueOf(str) converts String “Str” to Float object “fob”.

c. dob=Double.ValueOf(str) converts String “Str” to Double object “dob”.

d. lob=Long.ValueOf(str) converts String “Str” to Long object “lob”.

5. Converting String object to primitive numbers.

a.int i=Integer.parseInt(str)Converts String object “Str” to integer variable “i”.

b.long l=Long.parseLong(str)converts String object “Str” to long variable “l”.

Write java program to illustrate the use of some common wrapper class method.

Import java.io.*;

Class wrapper

Public static void main(String a[])

COMPUTER SCIENCE & ENGINEERING age 29


OOP WITH JAVA 15CS42T 2020-21

Float x=0.00f;

Float y=0.00f;

DataInputStream in= new DataInputStream(Stream in);

Try

System.out.println(“Enter two numbers”);

Float ob1=Float.valueOf(in.readLine());

Float ob2=Float.valueOf(in.readLine());

X=ob1.floatValue();

Y=ob2.floatValue();

Catch(Exception e)

Float sum=0.00f;

Float mul=0.00f;

Sum=x+y;

Mul=x*y;

System.out.println(“The sum of two numbers is=”+sum);

System.out.println(“two multiplication of two numbers=”+mul);

Annotations

COMPUTER SCIENCE & ENGINEERING age 30


OOP WITH JAVA 15CS42T 2020-21

Annotations provide data about a program that is not part of the program itself.

Annotation is used to merge additional java elements with the programming elements.

Java contains the following standard annotations.

Annotations Meaning

@Deprecated Compiler warns when deprecated java elements are used in non-

deprecated program.

@Overrides Compiler generated error when the method uses this annotation type

does not override the method present in the superclass.

In addition to this, java also contains some meta-annotations available in

“java.long.annotation” package they are.

Meta annotation Meaning

@Documented Indicates annotation of this type to be

documented by javadoc

@Inherited Indicates that this type is automatically

inherited.

@Retention Indicates the extended period using

annotation type.

@Target Indicates to which program element the

annotation is applicable.

The declaration of annotation is similar to interface but use the symbol “@” before keyword

interface.While using annotation, need to follow some guidelines

 Do not use “Extends” keyword.

COMPUTER SCIENCE & ENGINEERING age 31


OOP WITH JAVA 15CS42T 2020-21

 Do not use any parameter for a method.

 Do not use generic methods.

 Do not use “throws”

COMPUTER SCIENCE & ENGINEERING age 32


OOP WITH JAVA 15CS42T 2020-21

COMPUTER SCIENCE & ENGINEERING age 33

You might also like