classes-objects-methods
classes-objects-methods
2
Classes, Objects & Methods
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
• Syntax to declare a class:
class class_name
{
field declaration;
method declaration;
}
• Object
– An object is an instance of a class. Object
determines the behaviour of the class.
• object_name.variableName;
object_name.MethodName();
Object and Class Example
class Student{
int id=1; //field or data member or instance variable
String name=“ABC”;
• Example of Constructor
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();
}
}
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.
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);
}
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.
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);
}
}
Nesting of Methods
• 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.
• 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.
Own class
ü ü ü ü ü
Sub class
in same
package ü ü ü ü û
Other
classes
In same ü ü ü û û
package
Sub class
in other
package ü ü û ü û
Other
classes
In other ü û û û û
package
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
• Syntax to Declare an Array in java
dataType arr[];
dataType arrayRefVar[][];
For example:
For example:
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
4. length() This function returns the number of characters in a
String.
For example:
For example:
For Example:
String str = "0123456789";
System.out.println(str.substring(4));
Output : 456789
System.out.println(str.substring(4,7));
Output : 456
7. toLowerCase() This method returns string with all uppercase
characters converted to lowercase.
For Example:
Output : abcdef
For Example:
String str = "abcdef";
System.out.println(str.toUpperCase());
Output : ABCDEF
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
For example
String s1="java";
String s2="JAVA";
System.out.println(s1.equals(s2));
OUTPUT
false
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
For Example
String s1="java string";
s1.concat("is immutable");
Output
java string is immutable
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.
Important methods of StringBuffer class
Output : test123
• 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.
Output : test123
• 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.
Output
After Set, buffer = AMIL
• 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.
Output
length = 9
buff after new length = tutor
Vectors
• Vector implements a DYNAMIC ARRAY.
• Vectors can hold objects of any type and any
number.
• Vector class is contained in java.util package.
Difference between Vector & Array
Sr.
No. Vector Array
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};
Constructors of Vector Class
• Vector() -Constructs an empty vector.
– Vector list=new Vector();
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
• 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);
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
Output:
} WINTER
} SPRING
SUMMER
FALL
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.
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.
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...");
}
}
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...
}
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...
}
}
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.
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");
}
class Bike
{
final int speedlimit=80;//final variable
void run()
{
speedlimit=100;
}
public static void main(String args[])
{
Bike obj=new Bike(); Output: Compile Time Error
obj.run();
}
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();
}
Java final class
• If you make any class as final, you cannot extend it.
• Example of final class