Unit 3
Unit 3
Class
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical. It represents the
set of properties or methods that are common to all objects of one type.
A class is a template used to create objects. Classes are made up of members, the main
two of which are fields and methods. Fields are variables that hold the state of the object,
whereas methods define what the object can do—the so-called behaviors of the object.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
class <class_name>{
field;
method;
}
Example
class MyRectangle
int x, y;
int getArea()
return x * y;
Object
It is a basic unit of Object-Oriented Programming and represents the real life entities.
Object Creation
To access a (non-static) field or method from outside the defining class, an object of the
class must first be created. That’s done using the new keyword, which will create a new
object in the system’s memory.
Syntax
Example
}
An object is also called an instance. The object will contain its own set of instance
variables (non-static fields), which can hold values that are different from those of other
instances of the class.
In addition to creating the object, the members of the class that are to be accessible
beyond their package need to be declared as public in the class definition.
class MyRectangle
return x * y;
The members of this object can now be reached by using the dot operator after the
instance name:
r.x = 10;
r.y = 5;
}
Constructors in Java
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.
Every time an object is created using the new() keyword, at least one constructor is
called.
<class_name>()
{
Example:
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();
}
}
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
Example
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);
}
Constructor overloading 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.
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of A method is used to expose the behavior of
an object. an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default The method is not provided by the compiler
constructor if you don't have any constructor in any case.
in a class.
The constructor name must be same as the The method name may or may not be same
class name. as the class name.
Java Garbage Collection
In java, garbage means unreferenced objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.
ch
1) By nulling a reference:
1. mployee e=new Employee();
2. e=null;
3) By anonymous object:
1. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
Types of Method
o Predefined Method
o 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.
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 Declaration
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:
o Public: The method is accessible by all classes when we use public specifier in
our application.
o Private: When we use a private access specifier, the method is accessible only in
the classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
o 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.
Example:
void myPrint()
System.out.println("Hello");
Calling Methods
The preceding method will simply print out a text message. To invoke (call) it from the
main method, an instance of the MyApp class must be created first. The dot operator is
then used after the instance’s name in order to access its members, which include the
myPrint method.
public static void main(String[] args)
m.myPrint(); // "Hello"
Method Parameters
The parentheses that follow the method name are used to pass arguments to the method.
To do that, the corresponding parameters must first be added to the method declaration in
the form of a comma-separated list.
void myPrint(String s)
System.out.println(s);
A method can be defined to take any number of arguments, and they can have any data
types. Just ensure that the method is called with the same types and number of arguments
in the correct order.
m.myPrint("Hello"); // "Hello"
Return Statement
A method can return a value. The void keyword is then replaced with the data type the
method will return, and the return keyword is added to the method body with an
argument of the specified return type.
public class MyApp {
String getString()
return "Hello";
Return is a jump statement that causes the method to exit and return the specified value to
the place where the method was called. For example, the preceding method can be passed
as an argument to the println method because the method evaluates to a string.
Example:
class Addition {
int sum = 0;
}
class GFG {
public static void main (String[] args) {
}
}
Example:
import java.util.Scanner;
public class EvenOdd
{
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");
}
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 the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
}
Example:
Method Overloading
It’s possible to declare multiple methods with the same name as long as the parameters
vary in type or number. Called method overloading,
advantage of method overloading
In this example, we have created two methods, first add() method performs addition of
two numbers and second add method performs addition of three numbers.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
class Adder{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Static Method
A method that has static keyword is known as static method. In other words, a method
that belongs to a class rather than an instance of a class is known as a static method. We
can also 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.
Display.java
Example
class MyCircle
return newArea(r);
return pi*a*a;
float f = MyCircle.pi;
There are 2 ways that any computer language can pass an argument to a
subroutine.
Call by value:
Call by reference
1. Call by value: This method copies the value of an argument into a formal
parameter of the subroutine. Therefore, changes made to the parameter of the
subroutine have no effect on the argument used to call it.
In java when you pass a simple type of method, it is passed by value. Thus , what occurs
to the parameter that receive the argument has no effect outside the method.
class Operation{
int data=50;
}
}
2. Call by reference: A reference to an argument (not the value of the argument) is
passed to the parameter. Inside the subroutine, this reference is used to access the actual
argument specified in the call. This means that changes made to the parameter will
affected the argument used to call the subroutine.
In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed.
In this example we are passing object as a value. Let's take a simple example:
class Operation2{
int data=50;
}
}
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new class that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and fields in your current
class also.
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
single
multilevel
hierarchical
Types of Inheritance
There are various types of inheritance as demonstrated below.
Single Inheritance
Example:
class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
public class Tester {
public static void main(String[] arguments) {
Rectangle rect = new Rectangle();
rect.display();
rect.area();
}
}
Multilevel Inheritance
Example:
class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}
Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class.In below image, the class A serves as a base class for the derived class B,C
and D.
Example:
class Shape{
System.out.println("Area = "+(a*b));
int p = 2 * (a+b);
System.out.println("Permeter = "+p);
Area(){
a= 10;
b=20;
calculateArea(a,b);
int a,b;
Perimeter(){
a = 5;
b= 6;
calculatePerimeter(a,b);
class Main{
Visibility Control
It is possible to inherit all the members of a class by a subclass using keyword extends.
The methods and variables in the class are visible everywhere in the program. However,
it may be necessary to restrict the access to certain variables and methods from outside
the class. We can achieve this in java by applying visibility modifiers to the instance
variables and methods. The visibility modifiers are also known as access modifiers. Java
provides three types of visibility modifiers:
public
protected
private
public access:
Example:
public int x;
public void sum(){}
protected access:
the protected modifier makes the fields visible not only to all classes and subclasses in
the same package but also to subclass in the other packages.
private access:
private fields enjoy the highest level degree of protection. They are accessible only with
their own class. They cannot be inherited by subclasses and therefore not accessible in
subclasses. A method declared as private behaves like a method declared as final. It
prevents the method from being subclassed.
Super keyword
super keyword is used to refer base class. It can be used for two purposes:
Example:
class A{
public A(String a){
System.out.println(“Base class constructor ”+ a);
}
public void show(){
System.out.println(“Base class method”);
}
}
class B extends A{
public B(String s1){
super(“Object”);
System.out.println(“Sub class constructor ”+s1);
}
public void show(){
super.show();
System.out.println(“Base class method”);
}
}
class superex
{
public static void main(String arg[]){
B ob = new B(“Child Object”); //creating child class object
ob.show();
}
}
Overriding method
The methods defined in super class is inherited by its subclass and is used by the objects
created by the subclass. Method inheritance enables us to define and use methods
repeatedly in subclasses without having to define the method again in subclass.
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.
Example:
class Super{
int x;
Super(int x){
This.x = x;
}
void display(){
System.out.println(“Super x = ”+x);
}
}
class Sub extends Super{
int y;
Sub(int x,int y){
super(x);
this.y = y;
}
void display(){
super.display();
System.out.println(“Sub y = ”+y);
}
}
class Super{
public static void main(String arg[]){
Sub ob = new Sub(100,200);
ob.display();
}
}
Example:
class Animal{
void eat(){System.out.println("animal is eating...");}
}
// An abstract function
abstract void draw();
}
Abstract Method
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example
Example
Final Keyword
The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable.
final variable
If you make any variable as final, you cannot change the value of final variable. In other
words when a variable is declared with final keyword, its value can’t be modified,
essentially, a constant.
Example
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
final method
When a method is declared with final keyword, it is called a final method. A final
method cannot be overridden. The Object class does this—a number of its methods are
final. We must declare methods with the final keyword for which we are required to
follow the same implementation throughout all the derived classes.
Example
class Bike{
When a class is declared with final keyword, it is called a final class. A final class
cannot be extended(inherited).
final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}
Usage 2: The other use of final with classes is to create an immutable class like the
predefined String class. One cannot make a class immutable without making it final.