Unit-2 Classes Objects and Methods
Unit-2 Classes Objects and Methods
Unit-2 Classes Objects and Methods
UNIT-2
Defining a class :
Class is a user defined data type; it consists of variables and methods. These variables are
[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;
Methods of declaration :-
A class with only data fields and without methods has no life. Therefore it is necessary to add
Methods are declared inside the body of the class immediately after the declaration of
variables.
Example:-
class rect
Int l,w;
l=x;
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.
1. Rectangle obj;
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.
Object Name.variableName=value;
objectName.methodName(parameter_list);
Example:-
Class rectangle
int l,w;
l=x;
w=y;
Int rectarea()
int area=l*w;
return (area);
Class rect
int area1;
obj.getdata(10,20);
area1=rectarea();
System.out.println(“Area=”+area1);
Constructors :
Java supports a special type of method called “Constructor” that enables an object to
The constructor name should be same as class name. Java constructors does not specify any
Example:-
Class Rectangle
length=x;
width=y;
int rectarea()
return (length*width);
Class RectangleArea
{
COMPUTER SCIENCE & ENGINEERING age 5
OOP WITH JAVA 15CS42T 2020-21
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
Rectangle (intx )
length=width=x;
length=x;
width=y;
Int rectarea()
int area=length*width;
return (area);
Class result
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.
The static variables & static methods are without creating the object of the class. They are
Example -
Class operation
Return(x+y);
Return(x*y);
Class result
Int s=operation.add(10,20);
System.out.println(“Sum=”+s);
System.out.println(“Mul=”+m);
Nesting of method :
A method can be called by using only its name by another method of the same class. This is
Example:-
Class nesting
int m,n;
m=x;
n=y;
int largest ()
If (m>=n)
return (m);
else
return (n);
void display ()
System.out.println(“Largest no=”+large);
Class nestingTest
obj.display();
“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
“The inheritance allows subclass to inherit all the variables & method of the super class.
1. Single level inheritance: - One super class & only one sub class.
A
Super class
B
Sub class
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
Defining a subclass :
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
length=x;
width=y;
int area ()
int a=length*width;
return (a);
Rectangle
int height;
super(x, y);
height=z;
int volumearea()
int a1=length*width*height;
return (a);
Class result
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.
The first statement of the sub class constructor must use the keyword “Super” to call the
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()
int y;
super (a);
y=b;
Void display()
System.out.println(“Super x=”+x);
System.out.println(“Super y=”+y);
All methods & variables can be overridden by default. To present overriding a method or
Example:-
....
.....
Final classes :
Some times to prevent a class being further sub classes for security reasons. A class that
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
The “abstract” is a keyword. It can be used for both methods & classes. The abstract method
When a class contains at least one “abstract method” then the class should be declared as
“abstract”.
Example:-
Abstract class a
....
.....
.....
....
Example:-
Abstract class A
Class B extends A
Void show()
B obj=new B()
A.show();
It represents variable length arguments in methods. It makes the java code simple & flexible.
......
.....
Example:-
Class examplearg
String str1;
examplearg(String varg[])
str1=varg[i];
System.out.println(str1);
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.
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
4. Private Protected: - the private protected member’s visibility level to between “protected” &
modifier protected
Access
locations
same
package
in same
package
other
package
in other
package
String :
String is a sequence of character or collection character. In java, Strings are class objects and
1. String
2. String Buffer
In java, String is not an array of character; it does not hold “Null” value at the end . String
String name;
Name=new String(“Hello”); OR
String Arrays
String methods
4. s2=s1.trim()Remove white spaces at the beginning & end of the String s1.
Class StringOrdering
Int size=name.length;
String temp=null;
If(name[j].compareTo[i]<0)
Temp=name[i];
name[i]=name[j];
Name[j]=temp;
System.out.println (name[i]);
StringBuffer class
String class creates string with fixed-length. String Buffer class creates String with flexible
StringBuffer methods -
4.s1.setLegth(n) Sets the length of String s1 to n. If n less then s1.length then s1 will be truncked.
S1.setLength(3) s1=setLength(9)
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.
Advantages
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
Exmaple:-
Import java.util.*;
Class ExVector
Int length=org.length;
List.addElement(arg[i]);
List.insertElement(“COBOL”,2);
int size=list.size();
List.copyInto(listArray);
System.out.println(“list of Languages”);
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
Example:-
Class workingdays
Enum days
Sunday,Monday,Tuesday,Wednesday,Thursday,Friday Saturday;
Weekend(d);
If(d.equals(days.Sunday)
System.out.println(“value=”+d+”is a Holiday”);
Else
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.
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.
Write java program to illustrate the use of some common wrapper class method.
Import java.io.*;
Class wrapper
Float x=0.00f;
Float y=0.00f;
Try
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;
Annotations
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.
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
documented by javadoc
inherited.
annotation type.
annotation is applicable.
The declaration of annotation is similar to interface but use the symbol “@” before keyword