0% found this document useful (0 votes)
4 views

Java Unit 3 (3.2 3.3)

The document provides an overview of Java classes and objects, explaining that a class serves as a blueprint for creating objects, which are instances of classes. It details the structure of a class, including instance variables and methods, as well as the rules for declaring classes and creating objects. Additionally, it covers methods, constructors, and their types, including predefined and user-defined methods, along with examples to illustrate these concepts.

Uploaded by

anmolprasad0902
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Unit 3 (3.2 3.3)

The document provides an overview of Java classes and objects, explaining that a class serves as a blueprint for creating objects, which are instances of classes. It details the structure of a class, including instance variables and methods, as well as the rules for declaring classes and creating objects. Additionally, it covers methods, constructors, and their types, including predefined and user-defined methods, along with examples to illustrate these concepts.

Uploaded by

anmolprasad0902
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Class

Java Class

 In Java everything is encapsulated under classes. Class is the


core of Java language. It can be defined as a template that
describe the behaviors and states of a particular entity.
 A class defines new data type. Once defined this new type can be
used to create object of that type.
 int a;
 Object is an instance of class.
 In Java, to declare a class class keyword is used. A class contain
both data and methods that operate on that data. The data or
variables defined within a class are called instance variables and
the code that operates on this data is known as methods.
 Thus, the instance variables and methods are known as class
members.
class Person
{
int height; //data //instance variable
String color;
void eat() //method
{
}
}
Person p;
int a;
Rules for Java Class

 A class can have only public or default(no


modifier) access specifier.
 It must have the class keyword, and class must be followed
by a legal identifier.
 The variables and methods are declared within a set of curly
braces.
 A Java class can contains fields, methods, constructors, and
blocks. Lets see a general structure of a class.
Java class Syntax

class class_name
{
field;
method;
}
class Student
{
int rollno;//instance variable
String name;
void display(){ }//method
}
A simple class example
Suppose, Student is a class and student's name, roll number, age are
its fields and info() is a method. Then class will look like below.
class Student
{
String name;
int rollno;
int age;
void info()
{
// some code
}
}
 This is how a class look structurally. It is a blueprint for an
object. We can call its fields and methods by using the object.
 The fields declared inside the class are known as instance
variables. It gets memory when an object is created at
runtime.
 Methods in the class are similar to the functions that are
used to perform operations and represent behavior of an
object.
Java Object

 Object is an instance of a class while class is a blueprint of an


object. An object represents the class and consists
of properties and behavior.
 Properties refer to the fields declared with in class and
behavior represents to the methods available in the class.
 In real world, we can understand object as a cell phone that
has its properties like: name, cost, color etc and behavior like
calling, chatting etc.
 So we can say that object is a real world entity. Some real
world objects are: ball, fan, car etc.
 There is a syntax to create an object in the Java.
Java Object Syntax

className variable_name = new className();


Student st=new Student();

 Here, className is the name of class that can be anything


like: Student that we declared in the above example.
 variable_name is name of reference variable that is used
to hold the reference of created object.
 The new is a keyword which is used to allocate memory for
the object.
Example: Object creation

 Student std = new Student();


 Student s1=new Student(“abc”,1,18);
 Student s2= new Student(“ram”,2,23);
 S2=s1;
 System.out.println(s2.name+ s2.rollno+s.age)

 Here, std is an object that represents the class Student during


runtime.
 The new keyword creates an actual physical copy of the object
and assign it to the std variable. It will have physical existence and
get memory in heap area. The new operator dynamically
allocates memory for an object.
Name=“abc
”.rollno=1

s2
Program
public class Student
{
String name;
int rollno;
int age;
void info()
{
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args)
{
Student student = new Student();
// Accessing and property value
student.name = "Ramesh";
student.rollno = 253;
student.age = 25;
// Calling method
student.info();
}
}
In case, if we don’t initialized values of class fields then
they are initialized with their default values.
public class Student
{
String name;
int rollno;
int age;
void info()
{
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args)
{
Student student = new Student();
// Calling method
student.info();
}
}
O/P
Name: null
Roll Number: 0
Age: 0
Default values of instance variables

 int, byte, short, long -> 0


 float, double → 0.0
 string or any reference = null
 boolean → false
 These values are initialized by the default constructor of JVM
during object creation at runtime.
Employee class example
class Employee{
int id;
String name;
float salary;
void insert(int id, String name, float salary) {
this.id=id;
this.name=name;
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public classTestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Assignment
1. Create a class rectangle that is having two variables length
and width .Calculate the area of rectangle through a
method and display the result for two objects.
2. Create a class city that is having two variables city name
and population. Through the display method display the
information of two metro city.
Problem New.java
class City
{
String City_name;
int population;
void display(){
System.out.println(“City”+City_name+”population”+population}
}
class New
{
public static void main(String args[])
{
City ct= new City(); //create a object
ct.City_name=“Delhi”
ct.population= 1000000; ct.display();
}
Method
A method is a block of code or collection of statements or a
set of code grouped together to perform a certain task or
operation. It is used to achieve the reusability of code. We
write a method once and use it many times. We do not
require to write code again and again. It also provides
the easy modification and readability of code, just by
adding or removing a chunk of code. The method is executed
only when we call or invoke it.
Method Declaration

 The method declaration provides information about method


attributes, such as visibility, return-type, name, and
arguments. It has six components that are known as method
header, as we have shown in the following figure.
 Method Signature: Every method has a method signature. It is a part of
the method declaration. It includes the method name and parameter
list.
 Access Specifier: Access specifier or modifier is the access type of the
method. It specifies the visibility of the method. Java provides four types of
access specifier:
 Public: The method is accessible by all classes when we use public specifier
in our application.
 Private: When we use a private access specifier, the method is accessible
only in the classes in which it is defined.
 Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
 Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible only
from the same package only.
 Return Type: Return type is a data type that the method returns. It may
have a primitive data type, object, collection, void, etc. If the method does
not return anything, we use void keyword.
 Method Name: It is a unique name that is used to define the
name of a method. It must be corresponding to the functionality
of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.
 Parameter List: It is the list of parameters separated by a comma
and enclosed in the pair of parentheses. It contains the data type
and variable name. If the method has no parameter, left the
parentheses blank.
 Method Body: It is a part of the method declaration. It contains
all the actions to be performed. It is enclosed within the pair of
curly braces.
Types of Method

 There are two types of methods in Java:


 Predefined Method
 User-defined Method
Predefined Method
 In Java, predefined methods are the method that is already defined
in the Java class libraries is known as predefined methods. It is also
known as the standard library method or built-in method.
We can directly use these methods just by calling them in the
program at any point. Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to
the corresponding method runs in the background that is already
stored in the library.
 Each and every predefined method is defined inside a class. Such
as print() method is defined in the java.io.PrintStream class. It
prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Example
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
User-defined Method

 The method written by the user or programmer is known


as a user-defined method. These methods are modified
according to the requirement.
Example
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
Calling method
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt(); //6
//method calling
findEvenOdd(num); //findEvenOdd(6)
}}
//user defined method
public static void findEvenOdd(int num) //6
{
//method body
if(num%2==0)
System.out.println(num+" is even"); //6 is even
else
System.out.println(num+" is odd");
}
}
Addition of two number
public class Addition
{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c); //24
}
//user defined method
public static int add(int n1, int n2) //n1 and n2 are forma
l parameters
{
int s;
s=n1+n2; /19+5=24
return s; //returning the sum
}
}
Static Method

 A method that has static keyword is known as static method..


We can create a static method by using the
keyword static before the method name.
 The main advantage of a static method is that we can call it
without creating an object. It can access static data members
and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best
example of a static method is the main() method.
Example
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}
Instance Method

 The method of the class is known as an instance method.


It is a non-static method defined in the class. Before calling
or invoking the instance method, it is necessary to create an
object of its class. Let's see an example of an instance
method.
Example
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-
defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Constructor
 In Java, a constructor is a block of codes similar to the method. It is called when
an instance of the class is created. At the time of calling constructor, memory
for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one
constructor is called.
 It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default.
 There are two types of constructors in Java: no-arg constructor, and
parameterized constructor.
 Note: It is called constructor because it constructs the values at the time of
object creation. It is not necessary to write a constructor for a class. It is
because java compiler creates a default constructor if your class doesn't have
any.
Rules for creating Java constructor

 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
Types of Java constructors

 There are two types of constructors in Java:


 Default constructor (no-arg constructor)
 Parameterized constructor
Java Default Constructor

 A constructor is called "Default Constructor" when it


doesn't have any parameter.
 Syntax of default constructor:
<class_name>()
{
}
Example of default constructor
 //Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1() {System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Java Parameterized Constructor

 A constructor which has a specific number of parameters is


called a parameterized constructor.
 Why use the parameterized constructor?
 The parameterized constructor is used to provide different
values to distinct objects. However, you can provide the same
values also.
Example
/Java Program to demonstrate the use of the parameterized construc
tor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
o/p
111 Karan
222 Aryan
Constructor Overloading in Java

 In Java, a constructor is just like a method but without return


type. It can also be overloaded like Java methods.
 Constructor overloading in Java is a technique of having more
than one constructor with different parameter lists. They are
arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number
of parameters in the list and their types.
 Example of Constructor Overloading
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
o/p

111 Karan 0
222 Aryan 25

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy