Classes Objects Methods

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 85

Chapter No.

2
Classes, Objects & Methods

Mrs. Chavan P.P.


Defining a class, creating object
• A class is a group of objects which have common
properties. It is a template or blueprint from
which objects are created
• A class in Java can contain:
• Fields (data members)
• methods
• constructors
• blocks
• nested class and interface

Mrs. Chavan P.P.


• Syntax to declare a class:
class class_name
{
field declaration;
method declaration;
}

Mrs. Chavan P.P.


• Object
– An object is an instance of a class. Object
determines the behaviour of the class.

Student s1=new Student();


Student s2=new Student(2, “ABC”);
Student s3=new Student(s1);

Mrs. Chavan P.P.


accessing class members
• Instance variables and methods are accessed
via created objects.

• object_name.variableName;
object_name.MethodName();

Mrs. Chavan P.P.


Object and Class Example
class Student{
int id=1; //field or data member or instance variable
String name=“ABC”;

public static void main(String args[]){


Student s1=new Student(); //creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
} OUTPUT:
1
ABC
Mrs. Chavan P.P.
Constructors & methods
• Constructor in java is a special type of
method that is used to initialize the object.
• Java constructor is invoked at the time of
object creation. It constructs the values i.e.
provides data for the object that is why it is
known as constructor.
• Rules for creating java constructor
– Constructor name must be same as its class name
– Constructor must have no explicit return type

Mrs. Chavan P.P.


• Types of java constructors
– Default constructor (no-arg constructor)
– Parameterized constructor
– Copy constructor

• Example of Constructor

Mrs. Chavan P.P.


class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1 = new Student4(111,"Karan");
Student s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
} Mrs. Chavan P.P.
}
Constructor Overloading in Java
• In Java a class can have any number of
constructors that differ in parameter lists is
called Constructor overloading . The compiler
differentiates these constructors by taking into
account the number of parameters in the list
and their type.

Mrs. Chavan P.P.


class Student
{ public static void main(String args[])
int id; {
Student s1 = new Student(111,"Karan");
String name;
Student s2 = new Student(222,"Aryan",25);
int age;
Student(int i,String n) s1.display();
{ s2.display();
id = i; }
}
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
} Mrs. Chavan P.P.
Method Overloading in Java
• A Java method is a collection of statements
that are grouped together to perform an
operation.
• Creating Method
modifier returnType nameOfMethod (Parameter List)
{ // method body }
• If a class has multiple methods having same
name but different in parameters, it is known
as Method Overloading.

Mrs. Chavan P.P.


class Overloading
{
void sum(int a,long b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Overloading obj=new Overloading();
obj.sum(20,20);
obj.sum(20,20,20);
}
} Mrs. Chavan P.P.
Nesting of Methods

• When a method in java calls another method


in the same class, it is called Nesting of
methods.
• The below Java Program to Show the Nesting
of Methods.

Mrs. Chavan P.P.


import java.util.Scanner; public static void main(String[] args)
public class Nest_Methods {
{ Scanner s = new Scanner(System.in);
int area(int l, int b)
System.out.print("Enter length of cuboid:");
{ int l = s.nextInt();
int ar = 6 * l * b;
return ar; System.out.print("Enter breadth of cuboid:");
} int b = s.nextInt();
int volume(int l, int b, int h)
System.out.print("Enter height of cuboid:");
{ int h = s.nextInt();
int ar = area(l, b);
System.out.println("Area:"+ar); Nest_Methods obj = new Nest_Methods();
int vol ; int vol = obj.volume(l, b, h);
System.out.println("Volume:"+vol);
vol = l * b * h;
}
return vol; }
}

Mrs. Chavan P.P.


argument passing
• There are two ways to pass an argument to a
method. But there is only call by value in java
• call-by-value : In this approach copy of an
argument value is pass to a method. Changes
made to the argument value inside the method
will have no effect on the arguments.
• call-by-reference : In this reference of an
argument is pass to a method. Any changes made
inside the method will affect the argument value.
Mrs. Chavan P.P.
‘this’ Keyword
• this is a keyword in Java which is used as a
reference to the object of the current class,
with in an instance method or a constructor.
Using this you can refer the members of a
class such as constructors, variables and
methods.

Mrs. Chavan P.P.


class Student class TestThis2
{ {
int rollno; public static void main(String args[])
String name; {
Student s1=new Student(111,"ankit”);
Student(int rollno,String name)
Student s2=new Student(112,"sumit”);
{ s1.display();
this.rollno=rollno; s2.display();
this.name=name; }
} }
void display()
{
System.out.println(rollno+" "+name);
}
}

Mrs. Chavan P.P.


command line arguments
• Sometimes you will want to pass some
information into a program when you run it.
This is accomplished by passing command-line
arguments to main( ).
• A command-line argument is the information
that directly follows the program's name on
the command line when it is executed. They
are stored as strings in the String array passed
to main( ).

Mrs. Chavan P.P.


public class CommandLine
{
public static void main(String args[])
{
for(int i = 0; i<args.length; i++)
{
System.out.println("args[" + i + "]: " + args[i]);
}
} executing this program as shown here −

} D:\>javac CommandLine
D:\>java CommandLine this is a command line 200 -100

Mrs. Chavan P.P.


• Output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Mrs. Chavan P.P.


varargs: variable-length
arguments
• The varargs allows the method to accept zero
or multiple arguments.
• If we don't know how many argument we will
have to pass in the method, varargs is the
better approach.
• Syntax of varargs:
return_type method_name(data_type... variableName){}

Mrs. Chavan P.P.


class VarargsExample
{
static void display(String... values)
{
System.out.println("display method invoked ");
for(String s:values)
{ Output:
System.out.println(s); display method invoked
} display method invoked
hello
} display method invoked
My
public static void main(String args[]) Name
{ Is
varargs
display();//zero argument
display("hello");//one argument
display("my","name","is","varargs");//four arguments
}
}
Mrs. Chavan P.P.
garbage collection
• Garbage Collection is process of reclaiming
the runtime unused memory automatically. In
other words, it is a way to destroy the unused
objects.
• It is automatically done by the garbage
collector(a part of JVM) so we don't need to
make extra efforts.

Mrs. Chavan P.P.


finalize() method
• This method can be used to perform cleanup
processing.
• Objects may hold other non-object resources
such as file descriptors or system fonts. The
garbage collector cannot free these resources.
In order to free these resources we must use a
finalize() method.

protected void finalize(){}


Mrs. Chavan P.P.
Visibility Control
Java provides three types of visibility modifiers: public,
private and protected. They provide different levels of protection as
described below.

• Public Access: Any variable or method is visible to the entire class in which
it is defined. But, to make a member accessible outside with objects, we
simply declare the variable or method as public. A variable or method
declared as public has the widest possible visibility and accessible
everywhere.

• Friendly Access (Default): When no access modifier is specified, the


member defaults to a limited version of public accessibility known as
"friendly" level of access. The difference between the "public" access and
the "friendly" access is that the public modifier makes fields visible in all
classes, regardless of their packages while the friendly access makes fields
visible only in the same package, but not in other packages.
Mrs. Chavan P.P.
• Protected Access: The visibility level of a "protected" field lies in between
the public access and friendly access. That is, the protected modifier
makes the fields visible not only to all classes and subclasses in the same
package but also to subclasses in other packages

• Private Access: private fields have the highest degree of protection. They
are accessible only with their own class. They cannot be inherited by
subclasses and therefore not accessible in subclasses. In the case of
overriding public methods cannot be redefined as private type.

• Private protected Access: A field can be declared with two


keywords private and protected together. This gives a visibility level in
between the "protected" access and "private" access. This modifier makes
the fields visible in all subclasses regardless of what package they are in.
Remember, these fields are not accessible by other classes in the same
package.

Mrs. Chavan P.P.


Access public protected friendly private private
modifier → protected

Own class ✓ ✓ ✓ ✓ ✓
Sub class
in same ✓ ✓ ✓ ✓ 
package
Other
classes
In same ✓ ✓ ✓  
package
Sub class
in other ✓ ✓  ✓ 
package
Other
classes
In other ✓    
package
Mrs. Chavan P.P.
Arrays & Strings
Types of arrays, creating an array
• Array is a collection of similar type of
elements that have contiguous memory
location.
• Types of Array in java
– Single Dimensional Array
– Multidimensional Array

Mrs. Chavan P.P.


• Syntax to Declare an Array in java
dataType arr[];
dataType arrayRefVar[][];

• Instantiation of an Array in java


arrayRefVar=new datatype[size];
arrayRefVar[][]=new datatype[size][size];

• We can declare, instantiate and initialize the java


array together by:
int a[]={33,3,4,5};
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
Mrs. Chavan P.P.
class Testarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println(); Output:
} 123
} 245
} 445
Mrs. Chavan P.P.
strings
• In java, string is basically an object that
represents sequence of char values. The
java.lang.String class is used to create string
object.
• creating String object
String s="welcome"; (or)
String s=new String("Welcome");

Mrs. Chavan P.P.


public class StringExample
{
public static void main(String args[])
{
String s1="java“;
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");
System.out.println(s1);
System.out.println(s2); OUTPUT:
System.out.println(s3); java
} strings
} example

Mrs. Chavan P.P.


String Class Methods
1. charAt() This function returns the character located at the specified
index.

For example:

String str = “mmpolytechnic";


System.out.println(str.charAt(2));
Output : p

2. equalsIgnoreCase() This function determines the equality of two


Strings, ignoring their case (upper or lower case doesn't matters with this
fuction ).

For example:

String str = "java";


System.out.println(str.equalsIgnoreCase("JAVA"));
Mrs. Chavan P.P.
Output : true
3. indexOf() function returns the index of first occurrence of a substring
or a character. Forms of indexOf() method:
int indexOf(String str) It returns the index within this string of the first
occurrence of the specified substring.
int indexOf(String str, int fromIndex) It returns the index within this
string of the first occurrence of the specified substring, starting at the
specified index.

For Example:
String str=“MMPolytechnic";
System.out.println(str.indexOf('P'));
System.out.println(str.indexOf(‘i', 3));
String subString=“tech"; System.out.println(str.indexOf(subString));
System.out.println(str.indexOf(subString,8));

Output:
2
11
6
-1
Mrs. Chavan P.P.
4. length() This function returns the number of characters in a String.

For example:

String str = "Count me";


System.out.println(str.length());
Output : 8

5. replace() This method replaces occurances of character with a


specified new character.

For example:

String str = "Change me";


System.out.println(str.replace('m','M'));
Output : Change Me

Mrs. Chavan P.P.


6. substring() This method returns a part of the
string. substring() method has two forms,
String substring(int begin) It will return substring starting from
specified point to the end of original string.
String substring(int begin, int end) The first argument represents
the starting point of the substring and the second argument specify the
end point of substring.

For Example:
String str = "0123456789";
System.out.println(str.substring(4));

Output : 456789

System.out.println(str.substring(4,7));

Output : 456
Mrs. Chavan P.P.
7. toLowerCase() This method returns string with all uppercase
characters converted to lowercase.

For Example:

String str = "ABCDEF";


System.out.println(str.toLowerCase());

Output : abcdef

8. toUpperCase() This method returns string with all lowercase


character changed to uppercase.

For Example:
String str = "abcdef";
System.out.println(str.toUpperCase());

Output : ABCDEF

Mrs. Chavan P.P.


9. valueOf() This function is used to convert primitive data types into
Strings.

For example
int num=35;
String s1=String.valueOf(num); //converting int to String
System.out.println(s1+"IAmAString");

Output: 35IAmAString

10. trim() This method returns a string from which any leading and
trailing whitespaces has been removed.

For example
String str = " hello ";
System.out.println(str.trim());

output : hello

trim() method removes only the leading and trailing whitespaces.


Mrs. Chavan P.P.
11. toString() This method returns the string representation of
the object used to invoke this method.

12. equals() This method compares the two given strings


based on the content of the string. If any character is not
matched, it returns false. If all characters are matched, it
returns true.

For example

String s1="java";
String s2="JAVA";
System.out.println(s1.equals(s2));

OUTPUT
false

Mrs. Chavan P.P.


13. compareTo() It compares strings on the basis of
Unicode value of each character in the strings. It returns
positive number, negative number or 0.
• if s1 > s2, it returns positive number
• if s1 < s2, it returns negative number
• if s1 == s2, it returns 0

14. concat() This method combines specified string at the


end of this string. It returns combined string. It is like
appending another string.

For Example
String s1="java string";
s1.concat("is immutable");
Output
java string is immutable

Mrs. Chavan P.P.


StringBuffer class
• String creates strings of fixed length, while
StringBuffer creates strings of flexible length
that can be modified in terms of both length
and content.
• So StringBuffer class is used to create a
mutable string object i.e StringBuffer class is
used when we have to make lot of
modifications to our string.

Mrs. Chavan P.P.


Important methods of StringBuffer class

• append() This method will concatenate the string


representation of any type of data to the end of
the invoking StringBuffer object.

StringBuffer str = new StringBuffer("test");


str.append(123);
System.out.println(str);

Output : test123

Mrs. Chavan P.P.


• insert() This method inserts one string into another.
Here are few forms of insert() method.
– StringBuffer insert(int index, String str)
– StringBuffer insert(int index, int num)
– StringBuffer insert(int index, Object obj)
• Here the first parameter gives the index at which
position the string will be inserted and string
representation of second parameter is inserted
into StringBuffer object.

StringBuffer str = new StringBuffer("test");


str.insert(4, 123);
System.out.println(str);

Output : test123
Mrs. Chavan P.P.
• setCharAt() method sets the character at the
specified index to ch.
– setCharAt(int index, char ch)
• Here index is the index of the character to modify and
ch is the new character.

StringBuffer buff = new StringBuffer("AMIT");


buff.setCharAt(3, 'L');
System.out.println("After Set, buffer = " + buff);

Output
After Set, buffer = AMIL

Mrs. Chavan P.P.


• setLength() method sets the length of the character
sequence. The sequence is changed to a new character
sequence whose length is specified by the argument.
– setLength(int newLength)
newLength is the new length.

StringBuffer buff = new StringBuffer("tutorials");


System.out.println("length = " + buff.length());
buff.setLength(5);
System.out.println("buff after new length = " + buff);

Output
length = 9
buff after new length = tutor
Mrs. Chavan P.P.
Vectors
• Vector implements a DYNAMIC ARRAY.
• Vectors can hold objects of any type and any
number.
• Vector class is contained in java.util package.

Mrs. Chavan P.P.


Difference between Vector & Array
Sr.
Vector Array
No.
Vector can grow and shrink
1 Array can’t grow and shrink dynamically.
dynamically.
Vector can hold dynamic list of objects
2 Array is a static list of primitive data types.
or primitive data types.
Vector class is found in java.util Array class is found in java.lang (default)
3
package . package.
Vector can store elements of different
4 Array can store elements of same data type.
data types.
Vector class provides different methods For accessing element of an array no special
5 for accessing and managing vector methods are available as it is not a class,
elements. but a derived type.
Syntax : Syntax :
6
Vector objectname=new Vector(); datatype arrayname[]=new datatype[size];
7 Example: Vector v1=new Vector(); Example: int[] myArray={22,12,9,44};
Mrs. Chavan P.P.
Constructors of Vector Class
• Vector() -Constructs an empty vector.
– Vector list=new Vector();

• Vector(int size) -Constructs an empty vector


with the specified initial capacity.
– Vector list=new Vector(3);

Mrs. Chavan P.P.


Vector Methods
• addElement(Object) Adds the specified object to the
end of this vector, increasing its size by one.
Syntax :
vect_object.addElement(Object);
Example : If v is the Vector object ,
v.addElement(new Integer(10));

• capacity() Returns the current capacity of this vector.


Syntax :
vect_object.capacity();
Example : If v is the Vector object ,
v. capacity();
Mrs. Chavan P.P.
• elementAt(index) Returns the object at the
specified index.
Syntax :
vect_object.elementAt(index);
Example : If v is the Vector object ,
v.elementAt(3);

• firstElement() Returns the first object of this


vector.
Syntax :
vect_object.firstElement();
Example : If v is the Vector object ,
v. firstElement();
Mrs. Chavan P.P.
• lastElement() Returns the last object of the vector.
Syntax :
vect_object.lastElement();
Example : If v is the Vector object ,
v. lastElement();

• insertElementAt(Object, index) Inserts the specified


object in this vector at the specified index.
Syntax :
vect_object.insertElementAt(object,index);
Example : If v is the Vector object ,
v. insertElementAt(20,5);

Mrs. Chavan P.P.


• indexOf(Object) Searches for the first occurrence of
the given argument, testing for equality using
the equals method.
Syntax :
vect_object.indexOf(object);
Example : If v is the Vector object ,
v. indexOf(20);

• indexOf(Object, begin_index) Searches for the first


occurrence of the given argument, beginning the
search at index, and testing for equality using
the equals method.
Syntax :
vect_object.indexOf(object,begin_index);
Example : If v is the Vector object ,
v. indexOf(20,3);
Mrs. Chavan P.P.
• lastIndexOf(Object) Returns the index of the last
occurrence of the specified object in this vector.
Syntax :
vect_object.lastIndexOf(object);
Example : If v is the Vector object ,
v. lastIndexOf(20);

• isEmpty() Tests if this vector has no objects.


Syntax :
vect_object.isEmpty();
Example : If v is the Vector object ,
v. isEmpty();

Mrs. Chavan P.P.


• setElementAt(Object, index) Sets the object at
the specified index of this vector to be the
specified object.
Syntax :
vect_object.setElementAt(object, index);
Example : If v is the Vector object ,
v. setElementAt(30,5);

• setSize(int) Sets the size of this vector.


Syntax :
vect_object.setSize(size);
Example : If v is the Vector object ,
v. setSize(10); Mrs. Chavan P.P.
• size() Returns the number of objects in this vector.
Syntax : vect_object.size();
Example : If v is the Vector object ,
v. size();

• contains(Object) Tests if the specified object is present in this


vector.
Syntax : vect_object.cotains(object);
Example : If v is the Vector object ,
v. contains(30);

copyInto(Object[]) Copies the objects of this vector into the


specified array
Syntax : vect_object.copyInto(object[]);
Example : If v is the Vector object ,
v. copyInto(anArray); Mrs. Chavan P.P.
• removeAllElements() Removes all objects from this vector
and sets its size to zero.
Syntax : vect_object.removeAllElements();
Example : If v is the Vector object ,
v. removeAllElements();

• removeElement(Object)Removes the first occurrence of the


argument from this vector.
Syntax : vect_object.removeElement(object);
Example : If v is the Vector object ,
v. removeElement(30);

• removeElementAt(int)Deletes the component at the specified


index.
Syntax : vect_object.removeElementAt(index);
Example : If v is the Vector object ,
v. removeElementAt(5);
Mrs. Chavan P.P.
Wrapper classess in Java
• Wrapper class in java provides the mechanism to
convert primitive into object and object into
primitive.
• There are mainly two uses with wrapper classes.
• To convert simple data types into objects
constructors are used.
• To convert strings into data types (known as
parsing operations) methods of type parseXXX()
are used.

Mrs. Chavan P.P.


The automatic conversion of primitive into object is
known as autoboxing and vice-versa unboxing.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Mrs. Chavan P.P.


• Creating objects of the Wrapper classes
All the wrapper classes have constructors
which can be used to create the corresponding
Wrapper class objects.
• For example,
Integer intObject = new Integer (34);
Integer intObject = new Integer (i);
Float floatObject = new Float(f);
Double doubleObject = new Double(d);
Long longObject = new Long(l);

Where i,f,d,l are the variables of respective primitive


types.
Mrs. Chavan P.P.
The most common methods of the Integer wrapper class are summarized in
below table. Similar methods for the other wrapper classes are found in the Java
API documentation.

Method Purpose
int i =Integer.parseInt(str) returns a signed decimal integer value
equivalent to string str
str=Integer.toString(i) returns a new String object representing
the integer i
byte b=intObject.byteValue() returns the value of this Integer as a byte

double d=intObject.doubleValue() returns the value of this Integer as a


double
float f=intObject.float Value() returns the value of this Integer as a float

int i=intObject.intValue() returns the value of this Integer as an int

short s=intObject.shortValue() returns the value of this Integer as a short

long l=intObject.longValue() returns the value of this Integer as a long


Mrs. Chavan P.P.
• To convert any of the primitive data type value
to a String, we use the valueOf() method of
the String class which can accept any of the
eight primitive types.

String s1= String.valueOf('a'); // s1="a"
String s2=String.valueOf(25); // s2=“25"
String s3=String.valueOf(10.5); //s3=“10.5”

Mrs. Chavan P.P.


Enumerated Types
• Enum in java is a data type that contains fixed
set of constants.
• It can be used for days of the week (SUNDAY,
MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST) etc. The java enum
constants are static and final implicitly.

Mrs. Chavan P.P.


class EnumExample
{
public enum Season{ WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args)


{
for (Season s : Season.values())
System.out.println(s);
Output:
} WINTER
} SPRING
SUMMER
FALL

Mrs. Chavan P.P.


Inheritance
• Inheritance provided mechanism that
allowed a class to inherit property of another
class. When a Class extends another class it
inherits all non-private members including
fields and methods.

Mrs. Chavan P.P.


Types of inheritance in java
• On the basis of class, there can be three types of
inheritance in java: single, multilevel and
hierarchical.
• In java programming, multiple and hybrid inheritance
is supported through interface only.

Mrs. Chavan P.P.


Single Inheritance Example class Inheritance
{
class Animal public static void main(String args[])
{
{ Dog d=new Dog();
void eat() d.bark();
{ d.eat();
System.out.println("eating..."); }
} }
}
class Dog extends Animal Output:
{ barking... eating...
void bark()
{
System.out.println("barking...");
}
} Mrs. Chavan P.P.
Multilevel Inheritance Example
class Animal class Inheritance
{ {
void eat() public static void main(String args[])
{ {
System.out.println("eating..."); BabyDog d=new BabyDog();
} d.weep();
} d.bark();
class Dog extends Animal d.eat();
{ }
void bark() }
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{ Output:
System.out.println("weeping..."); weeping... barking... eating...
}
Mrs. Chavan P.P.
}
Hierarchical Inheritance Example
class Animal class Inheritance
{ {
void eat() public static void main(String args[])
{ {
System.out.println("eating..."); Cat c=new Cat();
} c.meow();
} c.eat();
class Dog extends Animal }
{ }
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
Output:
System.out.println("meowing..."); meowing... eating...
}
Mrs. Chavan P.P.
}
Method Overriding
• If subclass (child class) has the same method
as declared in the parent class, it is known
as method overriding in java.
• Rules for Java Method Overriding
– method must have same name as in the parent
class
– method must have same parameter as in the
parent class.

Mrs. Chavan P.P.


Example of method overriding

class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}

public static void main(String args[])


{
Bike obj = new Bike(); Output:
obj.run();
} Bike is running safely
Mrs. Chavan P.P.
Dynamic method dispatch
• Dynamic method dispatch is a mechanism by
which a call to an overridden method is
resolved at runtime. This is how java
implements runtime polymorphism.
• When an overridden method is called by a
reference, java determines which version of
that method to execute based on the type of
object it refer to.

Mrs. Chavan P.P.


Example of Dynamic method dispatch
public class TestDog
class Animal {
{ public static void main(String args[])
public void move() {
{ Animal a = new Animal();
Dog b = new Dog();
System.out.println("Animals can move");
a.move();
} b.move();
} a=b;
class Dog extends Animal a.move();
{ }
}
public void move()
{
System.out.println("Dogs can walk and run");
}
}

Mrs. Chavan P.P.


super keyword
In Java, super keyword is used to refer to
immediate parent class of a child class. In other
words super keyword is used by a subclass
whenever it need to refer to its immediate
super class.

Mrs. Chavan P.P.


Final Keyword In Java
The final keyword in java is used to restrict
the user. The java final keyword can be used in
many context. Final can be:
• variable
• method
• class

Mrs. Chavan P.P.


Java final variable
• If you make any variable as final, you cannot change the value of
final variable(It will be constant).
• Example of final variable

class Bike
{
final int speedlimit=80;//final variable
void run()
{
speedlimit=100;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run(); Output: Compile Time Error
}
} Mrs. Chavan P.P.
Java final method
• If you make any method as final, you cannot override it.
• Example of final method
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{ Output: Compile Time Error
Honda honda= new Honda();
honda.run();
}
} Mrs. Chavan P.P.
Java final class
• If you make any class as final, you cannot extend it.
• Example of final class

final class Bike{}

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run(); Output: Compile Time Error
}
}
Mrs. Chavan P.P.
Abstract class in Java
• A class that is declared as abstract is known
as abstract class. It needs to be extended and
its method implemented. It cannot be
instantiated.
• Example abstract class
abstract class A{}

Mrs. Chavan P.P.


abstract method
• A method that is declared as abstract and
does not have implementation is known as
abstract method.
• Example abstract method
abstract void printStatus();

Mrs. Chavan P.P.


Example of abstract class that has abstract method
abstract class Bike
{
abstract void run();
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda();
obj.run(); Output: running safely..
}
}
Mrs. Chavan P.P.
Java static keyword
• The static keyword in java is used for memory
management mainly. We can apply java static
keyword with variables, methods, blocks and
nested class. The static keyword belongs to
the class than instance of the class.
• The static can be:
– variable (also known as class variable)
– method (also known as class method)

Mrs. Chavan P.P.


Java static variable
• If you declare any variable as static, it is
known static variable.
• The static variable can be used to refer the
common property of all objects e.g. company
name of employees, college name of students
etc.
• The static variable gets memory only once in
class area at the time of class loading.

Mrs. Chavan P.P.


Java static method
• If you apply static keyword with any method,
it is known as static method.
• A static method belongs to the class rather
than object of a class.
• A static method can be invoked without the
need for creating an instance of a class.
• static method can access static data member
and can change the value of it.

Mrs. Chavan P.P.


Example of static variable & method
class Student public static void main(String args[])
{ {
int rlno; Student.change();
String name; Student s1 = new Student (1,"Karan");
static String clg = “MMP"; Student s2 = new Student(2,"Ayan");
static void change() Student s3 = new Student(3,"Suraj");
{
clg = ”MMPoly”; s1.display();
s2.display();
} s3.display();
Student(int r, String n) }
{ }
rlno = r;
name = n;
}
Output:
void display () 1 Karan MMPoly
{ 2 Aryan MMPoly
System.out.println(rlno+" "+name+" "+clg); 3 Suraj MMPoly
Mrs. Chavan P.P.
}

You might also like