KEMBAR78
Java Class | PDF | Method (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
7 views90 pages

Java Class

Uploaded by

p jayapal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views90 pages

Java Class

Uploaded by

p jayapal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 90

Java Programming

“Classes, Objects and Methods”


Defining a Class
A class is a user defined data type with a template that works to
define its properties. Once the class type has been defined, we can
create a variables using declaration. In java variables are called
as instances of the classes, which are the actual objects.
class class_name [extends superclassname]
{
fields declaration;
method declaration;
}class_name and super_classname are any valid java identifiers.
The keyword extends indicate that the properties of the super
class_name
Fields declaration
• Data is encapsulated in a class by placing data field inside the
body of class definition. These variables are called instance
variables because they are created whenever an object of the
class is initiated.
class rectangle
{
int length;
int width;
}
 The class rectangle contains two integer type variables. It is
allowed to declare one line.
 int length, width;
 These variables are called instance variables also called
nlp-ai@cse.iitb

member variables.
Method declaration

Methods are declared inside the body of the class but


immediately after the declaration of the instance variables.
.
type methodname (parameter-list)
{
method body
}
Method declaration
The body actually describes the operation to be performed on
the data lets us consider the following
class rectangle
{
int length;
int width;
void getdata(int x, int y)
{
length=x;
width=y;
}}
Program
class Rectangle
{
int length , int width;
void getData(int x, int y)
{
length=x;
width=y;
}
int rectarea()
{ int area=length*width;
return (area);
}nlp-ai@cse.iitb
Creating Objects
Objects in java are created using the new operator.
The new operator creates an object the specified
class and returns a reference to that object.

For example
Rectangle rect1;
rect1=new Rectangle();
Creating Objects
Bothe statement combine into one statement such as
Rectangle rect1= new Rectangle();

The Rectangle() method is the default constructor of the class so


that we can create any number of objects of Rectangle. Example
Rectangle rect1= new Rectangle();
Rectangle rect2=new Rectangle();

It is more important to understand that each object has its own copy
of instance variables of its class. This means any changes in object
that does not affect in another object.
Accessing the class members
We use the an object and dot operator as follows

Here object name is the name of the object, variable name is


the name of the instance variable inside the class
The instance variables of the Rectangle class may be accessed
and assigned values as follows.
rect1.length=10;
rect1.width=50;
Accessing the class members
In our program, the method getdata can be used as follows by
using object of the Rectangle class.

void getdata(int x, int y)


{
length=x;
width=y;
}
Program

nlp-ai@cse.iitb
Sample Program
Constructors
• A constructor is a block of codes similar to the method. It is called
when an instance of the class is created.
•It is a special type of method which is called to initialize the object.

•Every time an object is created using the new() keyword, at least


one constructor is called.
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and
synchronized
Program
Method Overloading
In java, it is possible to create methods that have same name,
but different parameter list and different definitions. This is
called method overloading. Method overloading is used when
objects are needed to perform similar task but different input
parameters.
When we call a method in an object, java matches the method
name , number of parameters and type of parameters to decide
which one of the definitions to execute. This process is known
as Polymorphism.
To create an overload method, we have to provide several
different method definitions in this class, all with same name
but different parameter lists. The difference may be the number
and type of arquments.
Program
Program
Program
Static Members
•Static variable in Java is variable which belongs to the class
and initialized only once at the start of the execution. It is a
variable which belongs to the class and not to object(instance ).
Static variables are initialized only once, at the start of the
execution. These variables will be initialized first, before the
initialization of any instance variables.

•A static method can call only other static methods and can not
call a non-static method from it.
•A static method can be accessed directly by the class name and
doesn’t need any object
•A static method cannot refer to "this" or "super" keywords in
anyway
class mathoperation Static Members
{
static float mul( float x,float y)
{
return(x*y);
}
static float div( float x,float y)
{
return(x/y);
}

}
class mathapp
{
public static void main(String arg[]) {
float a=mathoperation.mul(4.0,5.0);
float b=mathoperation.div(a,2.0);
Nesting Methods
The method can be called by using only its name by another
method of same class. This is known as nesting methods.
The following program that contains the class nesting defines
one constructor and two methods namely largest() and
display().The method display() calls the method largest() to
determine the largest of the two numbers and then display as
result.
class nesting
{
int m,n;
nesting(int x,int y)
{ m=x; n=y;}
Nesting Method
int largest()
{
if(m>=n)
return(m);
else
return(n);
}
void display()
{
int large=largest();
System.out.println(“The largest value”+large);
}}
Nesting Method
class nestingtest
{
public static void main(String arg[])
{
nesting nest=new nesting(50,40);
nest.display();
}
}
Ouput is
The largest value is 50
Inheritance: Extending class

Java classes can be used in several ways. classes can


be derived from other classes, thereby inheriting fields and
methods from those classes.
Definitions: A class that is derived from another class is called
a subclass (also a derived class, extended class, or child class).
The class from which the subclass is derived is called
a superclass (also a base class or a parent class).
Different forms of inheritance
Inheritance
Defining a Sub class

The keyword extends signifies that the properties of superclassname


extended subclassname.The subclass will contain own variables and
methods.
This kind of situation occurs when we want to add some more properties in
existing class without modifying it.
class Room
{
int length,breadth;
Room(int x,int y)
{
length=x;
breadth=y;
}
int area( )
{
return ( length * breadth);
}
class BedRoom extends Room
{
int height;
BedRoom(int x, int y, int z )
{
super(x,y);
height=z;
}
int volume( )
{
return ( length * breadth * height);
}
class inhertest
{
public static void main(String arg[])
{
BedRoom room1 = new BedRoom(14,12,10);
int area1=room1.area( );
int volume1=room1.volume();
System.out.println(“Area”+area1);
System.out.println(“Volume”+volume1);
}
}
Ouput is
Area 168
Volume 1680
Sub class constructor

A Subclass constructor is used to construct the instance


variables of the both subclass and superclass. The subclass
constructor uses the keyword super to invoke the constructor
method of the superclass. The keyword super used as follows.

a.Super only be used within a subclass constructor method.

b.The call to superclass constructor must appear as the first


statement within a subclass constructor.

c.The parameters in the super call must match the order and
type of instance variable declared in the superclass.
Multilevel inheritance
Method overriding

•If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
•In other words, If a subclass provides the specific
implementation of the method that has been declared by one of
its parent class, it is known as method overriding.
•Method overriding is used to provide the specific
implementation of a method which is already provided by its
superclass. Method overriding is used for runtime
polymorphism
•The method must have the same name as in the parent class,
The method must have the same parameter as in the parent
class. There must be an IS-A relationship (inheritance).
Final variables and Final Methods

•All the variables and methods can be overridden by default in


subclass. If we wish to prevent the subclasses from the
overriding members of superclass, we can declare them as final
using the final keyword.

For example

final int size=100;

final void showstatus()

Making a method as final that ensures that the functionally


defined in this method will never be altered in any way so that
we use the keyword final in front of methods.
Final Classes

A class that cannot be sub classed is called a final class. The


final class declared as follows.

final class aclass{ ………}

final class bclass extends smallclass { ……………….}

Declaring a class final prevents any unwanted extensions to the


class.it also allows the compiler to perform some optimizations
when a method of a final class is invoked.
Abstract class and Methods
An abstract class is a class that cannot be
instantiated (we cannot create objects of an abstract
class). In Java, we use the abstract keyword to
declare an abstract class.

abstract class Animal { //attributes and methods }


Finalizer methods

•finalize( ) method is a method of Object class which is


called just before the destruction of an object by the
garbage collector.
•After finalize( ) method gets executed completely,
the object automatically gets destroyed.
•The purpose of calling finalize method is to perform
activities related to clean up, resource deallocation etc.
Array Strings and Vectors

•An array is a collection of similar type of elements which has


contiguous memory location.For instance, we can define an
array name salary to represent set of salaries of a group of
employees.
•A particular values is indicated by writing a number called
index number. For example salary[10] it represents the salary of
10th employee while the complete set of values is referred to as
an array, the individual values are called elements.
One dimensional array

• A list of items can be given one variable name using only


one subscript and such a variable called a one
dimensional array
•Creating array
Creation of array involves three steps
Declaring an array
Creating an Array

•After declaring an array, we need to create it in the


memory. Java allows us to create an array using new
operator.
Initialization of an array

•The final step is to put values into the array created. This
process is known as initialization.
Initialization of an array

We can also initialize arrays automatically in the same


way as the ordinary variable when they are declared.
1.public class SortAsc {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {5, 2, 8, 7, 1};
6. int temp = 0;
7.
8. //Displaying elements of original array
9. System.out.println("Elements of original array: ");
10. for (int i = 0; i < arr.length; i++) {
11. System.out.print(arr[i] + " ");
12. }
1. //Sort the array in ascending order
2. for (int i = 0; i < arr.length; i++) {
3. for (int j = i+1; j < arr.length; j++) {
4. if(arr[i] > arr[j]) {
5. temp = arr[i];
6. arr[i] = arr[j];
7. arr[j] = temp;
8. }
9. }
10. }
11.
12. System.out.println();
1. //Displaying elements of array after sorting
2. System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
3. System.out.print(arr[i] + " ");
4. }
5. }
6.}
Output:

Elements of original array: 5 2 8 7 1


Elements of array sorted in ascending order: 1 2 5 7 8
Two dimensional Array

Two dimensional array are stored in memory with each dimension


array is indexed from zero to its maximum size minus one, the first
index selects the row and second index selects the column within
that row
Creating two dimensional array

Creating two dimensional arrays, we must follow the same steps


as that of simple arrays. We must create an array as follows.
Strings

We know that String represent a sequence of character in java,


strings are class object and implemented using two classes such as
String and StringBuffer.
A Java string is an object of String class so that A Java string is not
character array and is not NULL terminated. The String may be
declared and created as follows.
String-Example
String Arrays

We can create and use arrays that contains string. The statement
String itemarray[]=new String[3];
String-Example
String-Example
String-Example
StringBuffer Class

StringBuffer is a peer class of String, While String creates fixed


length of string, StringBuffer creates strings of flexible length that
can be modified in the terms of length and content. We can insert
the character and string in the middle of the string, or append
another string to end.
Manipulation of String
class stringmanipulation
{
public static void main(String arg[])
{
StringBuffer str=new StirngBuffer(“Object language”);
System.out.println(“The Original String is”+str);
System.out.println(“The length of the String is”+str.length());

for(int i=0;i<str,length();i++)
{
int p=i+1;
System.out.println(“The Character at position “ +p +”is”+str.charAt(i));

}
str.insert(6,”oriented”);
System.out.println(“Modified String”+str);
str.setCharAt(6,”-”);
System.out.println(“String Now” + str);
str.append(“improves the security”);
System.out.println(“Appended String”+str);
}
}
Vector

Vector is like the dynamic array which can grow or shrink its size.
Unlike array, we can store n-number of elements in it as there is no
size limit. It is a part of Java Collection framework since Java 1.2.
Vector
import java.util.*;
class langvector
{
public static void main(String args[])
{
Vector list=new Vector();
int length=args.length();
for(int i=0;i<length;i++)
{
list.addElement(args[i]);
}
list.insertElementAt(“COBOL”,2);
int size=list.size();
String listarray[]=new String[size];
list.copyInto(listarray);
System.out .println(“list of languages”);
for(int i=0;i<size;i++)
{
System.out.println(listarray[i]);
}
}
}
Compile and Run the program
C:/java> javac langvector.java

C:/java> java langvector Ada Basic C++ Fortran Java


List of language
Ada
Basic
COBOL
C++
Fortran
Java
}
Interfaces-Multiple Interitance

Java provides an alternative approach known as interface to support


the concept of multiple inheritance.Although a java class cannot be
a subclass of more than one superclass. It can implement more than
one interface so that java indirectly support the multiple inheritance
through the concept of interface.
Defining an interface
An interface is basically a kind of class,it contains methods and
variables it is called abstract methods and final fields.
An interface do not define any code to implement these methods and
data fields contains only constant.
Interfaces-Multiple Interitance

Defining an interface
An interface is basically a kind of class,it contains methods and
variables it is called abstract methods and final fields.
An interface do not define any code to implement these methods and
data fields contains only constant.
Interfaces-Multiple Interitance

Here an interface is a keyword and interfacename is any java valid


identifier here variables are declared as follows.

Note that all the variables are declared as constants. Methods


declaration only a list of methods without any body statement.
Here interface definition that contains two variables and one
method.
Interfaces-Multiple Interitance

Another example an interface

Extending an interface
Interfaces-Multiple Interitance

Another example an interface


Interfaces-Multiple Interitance
interface Polygon
{
void getArea(int length, int breadth);
}
class Rectangle implements Polygon
{
public void getArea(int length, int breadth)
{
System.out.println("The area of the rectangle is " + (length * breadth));
}}
class Main
{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}}
Interfaces-Multiple Interitance
import java.util.Scanner;
public class GetStudentDetails
{
public static void main(String args[])
{
String name;
int roll, math, phy, eng;
Scanner SC=new Scanner(System.in);
System.out.print("Enter Name: ");
name=SC.nextLine();
System.out.print("Enter Roll Number: ");
roll=SC.nextInt();
System.out.print("Enter marks in Maths, Physics and Englis
math=SC.nextInt();
phy=SC.nextInt();
eng=SC.nextInt();

You might also like