Classes Objects & Methods
Classes Objects & Methods
METHODS
CLASS
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.
String name;
Student(){
id = 0;
name = null;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student();
s1.display();
}
}
PARAMETERIZED CONSTRUCTOR
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
CONSTRUCTOR OVERLOADING
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
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();
}
}
‘THIS’ KEYWORD
1. this keyword can be used to refer current class instance
variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class
method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current
class instance.
1.TO REFER CURRENT CLASS INSTANCE VARIABLE.
class Student11{
int id;
String name;
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
4. TO PASS ANARGUMENT IN A METHOD
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
5. TO PASS ARGUMENT IN
CONSTRUCTOR CALL
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
COMMAND LINE ARGUMENTS
The java command-line argument is an argument i.e.
passed at the time of running the java program.
can pass N (1,2,3 and so on) numbers of arguments from
the command prompt.
EXAMPLE
1. class CommandLineExample{
2. public static void main(String args[])
3. {
4. System.out.println("Your first argument is: "+args[0
]); }
5. }
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
return_type method_name(data_type... variableName){}
Rules for varargs :
There can be only one variable argument in the
method.
Variable argument (varargs) must be the last argument.
EXAMPLE
class VarargsExample2{
for(String s:values){
System.out.println(s);
}
}
{
display();//zero argument
display("hello");//one argument
display("my","name","is","varargs");//four arguments
}
}
Output:display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs
GARBAGE COLLECTION
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime
unused memory automatically. In other words, it is a way
to destroy the unused 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.
Garbage collection is performed by a daemon thread
called Garbage Collector(GC). This thread calls the
finalize() method before object is garbage collected.
Advantage
It makes java memory efficient because garbage
collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector(a part
of JVM) so we don't need to make extra efforts.
OBJECT IS DEREFERENCED
1. By nulling a reference
Employee e=new Employee();
e=null;
3. By annonymous object
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.
The Garbage collector of JVM collects only those
objects that are created by new keyword. So if you
have created any object without new, you can use
finalize method to perform cleanup processing
(destroying remaining objects).
Syntax
protected void finalize()
{ }
OBJECT CLASS
The Object class is the parent class of all the classes in
java bydefault.
In other words, it is the topmost class of java.
Multidimensional Array
SINGLE DIMESION ARRAY
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Initialization Of Array
arrayRefVar=new datatype[size];
MULTIDIMESION ARRAY
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType []arrayRefVar[];
Initialization Of Array
int[][] arr=new int[3][3];//3 row and 3 column
EXAMPLE OF ARRAY
class Testarray{
public static void main(String args[]){
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
STRING IN JAVA
In java, string is basically an object that represents
sequence of char values.
There are two ways to create String object:
1. By string literal
String s="welcome";
2. By new keyword
String s=new String("Welcome");
STRING CLASS METHODS
char charAt(int index) returns char value for the particular index
String replace(char old, char new) replaces all occurrences of specified char value
StringBuffer(CharSequence seq)
2 This constructs a string buffer that contains the same characters as the specified
CharSequence.
StringBuffer(int capacity)
3 This constructs a string buffer with no characters in it and the specified initial
capacity.
StringBuffer(String str)
4
This constructs a string buffer initialized to the contents of the specified string.
STRINGBUFFER CLASS METHODS
StringBuffer append(String str)
This method appends the specified string to this
character sequence.
int capacity()
Vector()
1 This constructor is used to create an empty vector so that its internal data
array has size 10 and its standard capacity increment is zero.
Vector(int initialCapacity)
2 This constructor is used to create an empty vector with the specified
initial capacity and with its capacity increment equal to zero.
public static void main(String[] args) {
for (Season s : Season.values())
System.out.println(s);
}}
OUTPUT
WINTER
SPRING
SUMMER
FALL
INHERITANCE
Inheritance can be defined as the process where one class acquires
the properties (methods and fields) of another.
Extends keyword :
class Super{
.....
.....
}
}
TYPES OF INHERITANCE
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
CONSTRUCTOR
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
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types Of Constructor
class Circle{
double r;
public static void main(String[] args){
Circle c2 = new Circle(); // OK, default constructor
Circle c = new Circle(2.0); //error!!
}
}
CONSTRUCTOR EXAMPLE
class Circle{
double r;
public Circle (double r) {
this.r = r; //same name!
}
public static void main(String[] args){
Circle c = new Circle(2.0); //OK
Circle c2 = new Circle(); //error!!, no more default
}
}
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
Constructor name must be same as the Method name may or may not be same as
class name. class name.
OVERRIDING
What is overriding?
{
Overloading deals with multiple methods in the same class with the same
name but different signatures
Overriding deals with two methods, one in a parent class and one in a child
class, that have the same signature
68
FINAL INSTANCE VARIABLES
Principle of least privilege
Code should have only the privilege and access it needs to
accomplish its task, but no more
final instance variables
Keyword final
Specifies that a variable is not modifiable (is a constant)
final instance variables can be initialized at their
declaration
If they are not initialized in their declarations, they must be
initialized in all constructors
69
1 // Fig. 8.15: Increment.java
70
2 // final instance variable in a class.
OUTLINE
3
4 public class Increment
5 {
6 private int total = 0; // total of all increments Increment.java
7 private final int INCREMENT; // constant variable (uninitialized)
8
9 // constructor initializes final instance variable INCREMENT Declare final
10 public Increment( int incrementValue ) instance
11 { variable
12 INCREMENT = incrementValue; // initialize constant variable (once)
13 } // end Increment constructor
14
15 // add INCREMENT to total
Initialize final instance
16 public void addIncrementToTotal() variable inside a constructor
17 {
18 total += INCREMENT;
19 } // end method addIncrementToTotal
20
21 // return String representation of an Increment object's data
22 public String toString()
23 {
24 return String.format( "total = %d", total );
25 } // end method toIncrementString
26 } // end class Increment
STATIC CLASS MEMBERS
static fields
Alsoknown as class variables
Represents class-wide information
Used when:
all objects of the class should share the same copy of this instance variable
or
this instance variable should be accessible even when no objects of the
class exist
Can be accessed with the class name or an object name and a dot
(.)
Must be initialized in their declarations, or else the compiler will
initialize it with a default value (0 for ints)
71
What is an Abstract class?
Car Truck
- trunkCapacity: int - bedCapacity: int
Defining Abstract Classes
Transaction
- computeValue(): int
RetailSale StockTrade
- computeValue(): int - computeValue(): int
Defining Abstract Methods
Note: no implementation
public abstract class Transaction
{
public abstract int computeValue(); Transaction
- computeValue(): int