Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Java Notes3 PDF

Class forms the basis for object-oriented programming in Java. It defines both the data and code that will operate on the data. Objects are instances of a class that are dynamically allocated memory. A class contains variables called instance variables and methods that can access and manipulate the instance variables. Methods define reusable blocks of code that can be invoked on objects. Constructors initialize objects when they are created and can be overloaded like methods to support different initialization use cases.

Uploaded by

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

Java Notes3 PDF

Class forms the basis for object-oriented programming in Java. It defines both the data and code that will operate on the data. Objects are instances of a class that are dynamically allocated memory. A class contains variables called instance variables and methods that can access and manipulate the instance variables. Methods define reusable blocks of code that can be invoked on objects. Constructors initialize objects when they are created and can be overloaded like methods to support different initialization use cases.

Uploaded by

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

General form of a Class

class classname Class forms the basis for object-oriented programming in


{ //declare instance variables Java. It is the entity which binds all the data members
type var1; and functions together. It defines a new data type.
….. It is the template from which objects are created. It
type varN; defines both the data and the code that will operate on
//declare methods
the data.
main()
{ //main method body Objects are instances of a class. Object refers to the
} physical representation of the class in the memory.
type method1(parameter list) A class is created by using the keyword ‘class’.
{ //method body Methods and variables defined inside a class are called
} as members of the class.
…. Data members are also referred to as instance variables.
type methodN(parameter list) A class can be defined with no main method. A main
{ //method body method is required only if that class is the starting point
}
for the program.
} Prepared By – Asmita Ranade
Example of a Class
class Vehicle Here, a new class with name Vehicle is created. This declaration
{ does not create an actual object in the memory. So, no memory
int passengers; space is allocated to the class.
int fuelcap; To create an object of type Vehicle, we need to execute a statement
int kmpl; like –
} Vehicle van = new Vehicle();
With this statement an object of Vehicle class called as ‘van’ is created.
The ‘new’ operator dynamically allocates memory for the object ‘van’. So, in Java, all
class objects are dynamically allocated.
Each object contains its own copy of all instance variables ‘passengers’, ‘fuelcap’,
‘kmpl’ defined by the class.
To access these instance variables, a dot (.) operator is used.
‘object.member’ is the general form of using the dot operator.
Prepared By – Asmita Ranade
Methods in Java
A method is a collection of executable statements or instructions which
perform a specific task.
Methods are the subroutines which manipulate the data defined by the class and
may provide access to that data.
Each method has a name which is used to call the method. This can be any legal
identifier other than those already used by other items within the current scope.
Do not use Java’s keywords for method names.
The method may return a value to the calling method. In Java, every method
should be a member of some class.
Prepared By – Asmita Ranade
Methods in Java
The general form of a method is –
modifier returntype methodname(parameter list) throws exception
{
method body
}
Method declaration contains the following components –
• Modifier – Modifiers or Access specifiers in Java help to restrict the scope of a method.
Java defines four different types of access specifiers or modifiers – public, protected,
private and default (no keyword required) .
• Return type – the data type of the value returned by the method or void if it does not
return a value.
• Parameter list – comma separated list of parameters are defined preceded with data type.
It is not a mandatory component.
• Exception list – list of exceptions the method can throw.
• Method body – List of instructions are enclosed within braces. Prepared By – Asmita Ranade
Example - Method
Return type Method name Parameters

default access
specifier used int numberSum (int x, int y, int z)
{ Local variable

int sum;
sum = x+ y + z; Method body

Return statement return (sum);


}
Method Signature – numberSum(int x, int y, int z)
Prepared By – Asmita Ranade
Calling a Method
Set of statements in the method body will be executed only when the method is
called.
When the method is executed, Java run-time system transfers control to the code
defined inside the method.
After the statements inside the method body are executed, control is returned to
the calling routine and the execution resumes with the line of code following the
method call.
When a method uses an instance variable (defined by its class itself) , it does so
directly, without explicit reference to an object and without the use of dot (.)
Prepared By – Asmita Ranade
operator.
Returning a value
If the method returns a value then the value is returned to the calling method.
Following are the important points regarding returning values –
• The type of data returned by a method must be compatible with the return type
specified by the method.
• The variable receiving the value returned by the method must also be
compatible with the return type of the method.

Prepared By – Asmita Ranade


Parameters in a method
A parameter is a variable defined by a method that receives a value when
the method is called. Parameters allow a method to be generalized. A
parameterized method can operate on a variety of data and/or be used in a
number of slightly different situations.
int product (int i , int j)
{
Here, i and j are called as Parameters.
return i * j;
}

int n=5, m=12; Here, n and m are called as Arguments.


An argument is a value which is passed to a method when it is
int p1=product (n , m); invoked.
Prepared By – Asmita Ranade
Constructors
A constructor initializes an object when it is created. It has the same name as its
class and is syntactically similar to a method. Constructors do not have any
explicit return type, not even void.
Constructor is basically used to initialize the instance variables defined in the
class or to perform any other startup procedures required to construct an object.
All classes in Java have constructors even if we do not explicitly define it. Java
automatically provides a default constructor to every class. In such a case, non-
initialized instance variables have their default values (zero for numeric types,
null for reference types, false for boolean types). Default constructor will no
longer be used when a constructor is explicitly defined for the class.
Prepared By – Asmita Ranade
Example explained - Constructor
class Example
{ int x ;
Here, the constructor initializes the
Example ( ) Constructor instance variable x of Example
{
x=10; class to value 10.
}
}
class ExampleDemo
{ public static void main (String args[])
{
This constructor is automatically
Example e1 = new Example( );
System.out.println (e1.x); called when new operator is used
}
} to create the object.

Prepared By – Asmita Ranade


Example explained – Parametrized Constructor
class Example
{ int x ;
Here, the constructor has a
Parameterized
Example (int num ) Constructor
parameter num which is used to
{
x=num; initialize x.
}
}
class ExampleDemo
{ public static void main (String args[])
{
Observe that each object is
Example e1 = new Example( 100);
Example e2 = new Example (20); initialized as specified by the
System.out.println (e1.x);
System.out.println(e2.x); parameter’s value to its
}
}
constructors. Prepared By – Asmita Ranade
Method Overloading
In Java, it is possible to declare two or more methods within a class that have the same
name, as long as their parameter declarations vary. Such methods are called as
overloaded methods and the process is called as Method Overloading.
Method overloading is also known as Compile-time Polymorphism or Early binding
in Java.
Overloaded methods must differ in the datatype of the parameters and/or the number of
their parameters. i.e. methods should have different signatures.
When an overloaded method is invoked, Java uses the datatype and/or number of
arguments to determine which version of the overloaded method to call. Java executes
the version of the method whose parameters match the arguments used in the call.
Prepared By – Asmita Ranade
Constructor Overloading
In Java, similar to methods, constructors can also be overloaded. It allows the programmer
to construct objects in a variety of ways.
Constructor Overloading can be defined as the concept of having more than one
constructor with different parameters so that every constructor can perform a different
task.
Proper overloaded constructor is called based upon the parameters specified when new is
executed.
Returning Objects
A method can return any type of data, including class types which we create. When an object
is returned by a method, it remains in existence until there are no more references to it. So,
an object won’t be destroyed just because the method which created it terminates.
Prepared By – Asmita Ranade
Inheritance
Inheritance is one of the key OOP feature supported in Java. It allows creation of
hierarchical classifications. Its main feature is the reuse of code. Using Inheritance, we
can create a general class which defines certain common traits. This class can then be
inherited by other classes, each one adding its own unique elements to it.
A class that is inherited is called as Superclass / Parent Class.
The class that does the inheriting is called as Subclass / Child Class.
A subclass inherits all the members defined by the superclass and can add its own
unique set of elements to its definition.
Java supports inheritance by allowing one class to incorporate another class into its
declaration by using the ‘extends’ keyword.
Prepared By – Asmita Ranade
Inheritance Syntax

class superclassname
{
//data members Here, ‘extends’ keyword is used
// methods to create a subclass of the
}
superclass which is already
class subclassname extends superclassname defined.
{
//class body
}

Prepared By – Asmita Ranade


Important Points - Inheritance
• One major advantage of Inheritance is that once we have created a superclass which
defines attributes common to a set of objects, it can be used to create any number of
more specific sub classes. Each subclass can precisely define its own classification.
• We can specify only one superclass for any subclass. Java does not support
inheritance of multiple super classes into a single subclass.
• Java allows us to create a hierarchy of inheritance in which a subclass becomes
superclass of another subclass.
• A superclass is a complete independent standalone class. Being a superclass for a
subclass does not mean that the superclass cannot be used by itself.
• No class can be a superclass of itself.
Prepared By – Asmita Ranade
Java’s Access Modifiers
Member access control is achieved through the use of 3 access modifiers – public, private
and protected.
If no access modifier is used, the default access setting is assumed. An access modifier
precedes the rest of a member’s type specification i.e. it must begin a member’s declaration
statement. E.g. public int width;
Public – When a member of a class is defined using public access specifier then that member
can be accessed by any other code in the program including methods defined inside other
classes.
Private – When a member is defined using private access specifier then that member can be
accessed only by other members of its class. So, methods defined in other classes cannot
access a private member of another class.
Prepared By – Asmita Ranade
Using super in Inheritance
Whenever a subclass needs to refer to its immediate superclass, it can do so by
using the ‘super’ keyword.
‘super’ has two forms –
1. super keyword can be used to call the superclass constructor.
Syntax – super (parameter list);
here, parameter list specifies any parameters needed by the superclass
constructor. super() must always be the first statement to be executed inside a
subclass constructor. Note that when a subclass calls super(), it is calling the
constructor of its immediate superclass.
Prepared By – Asmita Ranade
Using super in Inheritance (contd.)
2. super keyword can also be used to access a member of the superclass that
has been hidden by a member of a subclass.
Syntax – super.member
Here, member can be either a method or an instance variable.

Prepared By – Asmita Ranade


Multilevel Inheritance
We can build hierarchies that contain as many layers of inheritance as we wish.
We can use a subclass as a superclass of another class.

A
E.g. Consider 3 classes A, B and C. C is the subclass of B and B is
the subclass of A.
B
In such situation, each subclass inherits all of the traits found in all
of its super classes. Here, C inherits all aspects of B and A.
C

Prepared By – Asmita Ranade


Method Overriding
When a method in a subclass has the same return type and signature as a method
in its superclass, then the method in the subclass is said to ‘override’ the method
in the superclass. When an overridden method is called from within a subclass, it
will always refer to the subclass version of the method. The version of the
method defined in the superclass will remain hidden.
If we want to access the superclass version of an overridden method, we can do
so by using ‘super’ keyword.
Method overriding occurs only when the signatures of the two methods are
identical. If they are not, then the methods are overloaded and not overridden.
Prepared By – Asmita Ranade
final keyword
In Java, it is easy to prevent a method from being overridden or a class from being inherited
by using the keyword ‘final’.
• final method - To prevent a method from being overridden, specify final as a modifier at
the start of its declaration. Methods declared as final cannot be overridden.
• final class - We can prevent a class from being inherited by preceding its declaration
with final. Declaring a class as final implicitly declares all of its methods as final too.
• final variable - final can also be applied to member variables to create constants. So, its
value cannot be changed throughout the program. Such a variable should always be
initialized when it is declared.
• It is illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete implementations.
Prepared By – Asmita Ranade
final method - Example
class A
{ final void display() //final method
{ System.out.println("Display from final method of class A");
File saved with
}
name
}
Bfinal.java
class B extends A
{ void display() //ERROR, cannot override
{ System.out.println("Display from class B");
}
}

Prepared By – Asmita Ranade


final class - Example
final class A
{ File saved with name
// data members
// methods Afinal.java
}
class B extends A //ERROR
{
// class body
}

Prepared By – Asmita Ranade


final member variable - Example
class memfinal
{ public static void main(String args[]) File saved with name
{ final int val = 12;
int x = 5; memfinal.java
val = val + x;
System.out.println("Value of val = " + val);
}
}

Prepared By – Asmita Ranade

You might also like