Java Object-Oriented Programming Basics
Java Object-Oriented Programming Basics
Class Fundamentals
In Java, everything is encapsulated under classes. Class can be defined as a template/blueprint
that describes the behaviors/states of a particular entity. A class defines new data type. Once
defined, this new type can be used to create object of that type. Object is an instance of class.
You may also call it as physical existence of a logical template class.
A class is declared using class keyword. A class contains both data and code that operate on that
data. The data or variables defined within a class are called instance variables and the code that
operated on this data is known as methods.
The General Form of a Class
class classname [ extends baseclass implements interface1, interface2 ]
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Rules for Java Class
A Class can have only public or default(no modifier) access specifier.
It must have the class keyword, and class must be followed by a legal identifier.
It may optionally extend one parent class. By default, it will extend [Link]
It may optionally implement any number of comma-separated interfaces.
The class’s variables and methods are declared within a set of curly braces {}
Each .java source file may contain only one public class.
Finally the source file name must match the public class name and it must have a .java
suffix.
Objects
Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name and object type.
Instantiation: The 'new' key word is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
The general syntax for declaring object
classname ref_var;
ref_var = new classname ( );
Here, ref_var is a variable of the class type being created. The classname is the name of the class
that is being instantiated. After the first line executes, ref_var contains the value null, which
indicates that it does not yet point to an actual object. The next line allocates an actual object and
assigns a reference to it to ref_var.
The new operator dynamically allocates memory for an object. The class name followed by
parentheses specifies the constructer for the class. A constructer defines what occurs when an
object of a class is created.
Assigning object reference variables
When you assign one object reference variable to another object reference variable, you are not
creating a copy of the object; you are only making a copy of the reference.
Methods
• A method is a collection of statements that are grouped together to perform an operation.
• A method is a block of code which only runs when it is called.
The general form of a method is
type methodname (parameter-list) {
// body of method
}
Every method should specify the type of data to be returned. This can be any valid type,
including class types that you create. If the method does not return a value, its return type must
be void. The name of the method can be any valid identifier. The parameter-list is a sequence of
type and identifier pairs separated by commas. Parameters are variables that receive the value of
the arguments passed to the method when it is called.
Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
return value;
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an instance variable
the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor ();
/* Now call a variable as follows */
[Link];
/* Now you can call a class method as follows */
[Link]()
Example1
class Pencil
{
private String color = "red";
Overloading Constructors
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated
on the basis of their type of parameters or number of parameters. Constructor overloading is not
much different than method overloading.
Example
class Point
{
private int x,y;
Point() //default constructor
{
x = y = 0;
}
Point(int i, int j) //parameterized constructor with 2 argument
{
x = i;
y = j;
}
public void display()
{
[Link](x+" , "+y);
}
public static void main(String[] args)
{
Point p1 = new Point();
Point p2 = new Point(10,20);
[Link]();
[Link]();
}
}
Output
0, 0
10, 20
this keyword
this keyword in java can be used inside any method to refer to the current object. (i.e.) ‘this’ is
always a reference to the object on which the method was invoked.
Instance variable hiding
When a local variable has the same name as an instance variable, the local variable hides the
instance variable. As the keyword ‘this’ lets you refer directly to the object, you can use it to
resolve any name space collisions that might occur between instance variables and local
variables.
Usage of this keyword
class TestThis2{
public static void main(String args[]){
Student s1=new Student(101,"Raj",8000f);
Student s2=new Student(102,"Sundar",7000f);
[Link]();
[Link]();
}
}
Output
101 Raj 8000
102 Sundar 7000
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.
public static void gc(){}
Example
public class TestGarbage1{
public void finalize(){[Link]("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
[Link]();
}
}
Output
object is garbage collected
object is garbage collected
Output
2018699554
end of garbage collection
finalize method called
Overloading Methods
If two or more method in a class has same name but different parameter list, it is known as
method overloading. Java implements static polymorphism using method overloading. Method
overloading can be done by changing number of argument or by changing the data type of
argument. If two or more methods have same name and same parameter list, but differs in return
type are not said to be overloaded method.
When an overloaded method is called, java look for match between the arguments to call the
method and method’s parameters. This match need not always be exact. Sometimes when exact
match is not found, Java automatic type conversion plays a vital role.
Example
class Calculate
{
public void sum(int a, int b){
[Link]("Sum = "+(a+b));
}
public void sum(double a, double b){
[Link]("Sum = "+(a+b));
}
public void sum(int a, int b, int c){
[Link]("Sum = "+(a+b+c));
}
public static void main(String[] args){
Calculate c = new Calculate();
[Link](3,4); //sum(int a, int b) is called
[Link](1,2,3); //sum(int a, int b, int c) is called
[Link](10.23,23.3); // sum(double a, double b) is called
}
}
Output
Sum = 7
Sum = 6
Sum = 33.53
Using Objects as Parameters
In Java, objects can be passed as parameters to methods, just like primitive data types. When an
object is passed as a parameter, the reference to the object is passed, not the actual object itself.
This means that changes made to the object inside the method will affect the original object.
Example: Passing Objects as Parameters
class Person {
String name;
// Constructor
Person(String name) {
[Link] = name;
}
Output:
Copy codeBefore modification: Alice
After modification: John Doe
Argument Passing
There are two ways that java can pass an argument to a method.
Call by value
This method copies the value of an argument into formal parameter of the method.
Changes made to the parameter of the method have no effect on the argument used to
call it.
In Java, when you pass a simple type to a method, it is passed by value.
Call by Reference
In this method, a reference to an argument (not the value of the argument) is passed to
the parameter. Changes made to the parameter will affect the argument used to call
the method.
In java, objects are always passed by reference.
Example
Call by value
public class SwapByValue {
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
[Link]("After swap method: a = " + a + ", b = " + b);
}
public static void main(String[] args) {
int a = 5;
int b = 10;
[Link]("Before swap: a = " + a + ", b = " + b);
swap(a, b);
}
}
OUTPUT
Before swap: a = 5, b = 10
After swap method: a = 10, b = 5
Call by reference
class Number {
int value;
Number(int value) {
[Link] = value;
}
}
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
Returning Objects
A method can have any type of data, including class types that you create, as argument and can
return any type including objects.
Example
public class Point {
int x,y;
Point()
{
x = y = 0;
}
Point(int i,int j)
{
x = i;
y = j;
}
static Point addPoint(Point p1, Point p2 ) //Object as argument and return value
{
Point p3 = new Point();
p3.x = p1.x+p2.x;
p3.y = p1.y+p2.y;
return p3;
}
void display()
{
[Link](x+" , "+y);
}
public static void main(String[] args)
{
Point p1 = new Point(10,20);
Point p2 = new Point(1,2);
Point p3 = addPoint(p1, p2);
[Link]();
[Link]();
[Link]();
}
}
Output
10 , 20
1,2
11 , 22
Recursion
Recursion is the process of defining something in terms of itself. In java programming, recursion
is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.
Example
public class FactNo {
static int Fact(int n) //Recursive Function
{
if(n <=1)
return 1;
else
return n*Fact(n-1);
}
public static void main(String[] args)
{
[Link](Fact(5));
}
}
Output
120
Introducing Access Control
We can control the access level for class member variables and methods through access
specifiers.
The four access levels are:
Visible to the package. No modifiers are needed.
Visible to the class only- private.
Visible to the world- public.
Visible to the package and all subclasses- protected.
Default Access Modifier - No keyword: Default access modifier means we do not explicitly
declare an access modifier for a class, field, method, etc. A variable or method declared without
any access control modifier is available to any other class in the same package. The fields in an
interface are implicitly public static final and the methods in an interface are by default public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
Private Access Modifier - private: Methods, Variables and Constructors that are declared
private can only be accessed within the declared class itself. Private access modifier is the most
restrictive access level. Class and interfaces cannot be private. Variables that are declared private
can be accessed outside the class if public getter methods are present in the class. Using the
private modifier is the main way that an object encapsulates itself and hides data from the outside
world.
Example
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is a compile-time error.
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
Protected Access Modifier - protected: Variables, methods and constructors which are declared
protected in a super class can be accessed only by the subclasses in other package or any class
within the package of the protected members' class. The protected access modifier cannot be
applied to class and interfaces. Methods, fields can be declared protected, however methods and
fields in an interface cannot be declared protected. Protected access gives the subclass a chance
to use the helper method or variable, while preventing a nonrelated class from trying to use it.
Example
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Output
Hello
Static methods
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.
main() method is the most common example of static method. Main() method is declared
as static because it is called before any object of the class is created
Limitations of static method
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in anyway
Example using Static variable and static method
class Circle
{
static double PI = 3.1416; //Static variable
static int area(int r){ //Static method
return PI*r*r;
}
}
class Test
{
public static void main(String args[]){
[Link](" Area of Circle = " +[Link](5));
}
}
Get memory only once Get new memory each time a new object is
created
class A
{
final void print()
{
[Link](" base class");
}
}
class B extends A
{
// error ! final methods cannot be overridden
void print()
{
[Link](" sub class ");
}
}
It is used to prevent Inheritance.
If a class is declared final, it cannot be inherited. String class in [Link] package is an
example of final class.
final class A
{
// methods and variables of a class
}
// error , A cannot be inherited
class B extends A
{
// methods and variables of a class
}
Program using final and static keywords
import [Link].*;
public class AreaOfShapes
{
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
}
}
}
// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
[Link] nestedObject = new [Link]();
[Link]();
}
}
Output
outer_x=10
outer_private=30
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;
// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
[Link]("outer_x = " + outer_x);
}
}
}
// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
[Link] innerObject = [Link] InnerClass();
[Link]();
}
}
Output
outer_x=10
outer_y=20
outer_private=30
Example
class outer //Enclosing class
{
int outer_x =10;
Output
java
strings
example
// 3. Substring
[Link]("Substring (7 to 12): " + [Link](7, 12));
// 4. String comparison
[Link]("Equals: " + [Link](str2));
[Link]("Equals Ignore Case: " + [Link](str2));
// 5. Concatenation
[Link]("Concatenation: " + [Link](" How are you?"));
// 6. Replace characters
[Link]("Replace 'World' with 'Java': " + [Link]("World", "Java"));
// 8. Trim whitespace
String str3 = " Trim me! ";
[Link]("Trimmed: '" + [Link]() + "'");
// 9. Split string
String[] words = [Link](", ");
[Link]("Split:");
for (String word : words) {
[Link](word);
}
OUTPUT
Length: 13
Character at index 7: W
Substring (7 to 12): World
Equals: false
Equals Ignore Case: true
Concatenation: Hello, World! How are you?
Replace 'World' with 'Java': Hello, Java!
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Trimmed: 'Trim me!'
Split:
Hello
World!
Contains 'World': true
StringBuffer Class
StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.
Mutable String
A string that can be modified or changed is known as mutable string. StringBuffer is used for
creating mutable string.
Constructors of StringBuffer class
StringBuffer()-creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str)- creates a string buffer with the specified string.
StringBuffer(int capacity)- creates an empty string buffer with the specified capacity as
length.
Methods of StringBuffer class
append(String s)- is used to append the specified string with this string. The append()
method is overloaded like append(char), append(boolean), append(int), append(float),
append(double) etc.
Example
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
insert(int offset, String s)-is used to insert the specified string with this string at the
specified position. The insert() method is overloaded like insert(int, char), insert(int,
boolean), insert(int, int), insert(int, float), insert(int, double) etc.
Example
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}
replace(int startIndex, int endIndex, String str)- is used to replace the string from specified
startIndex and endIndex.
Example
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
delete(int startIndex, int endIndex)- is used to delete the string from specified startIndex
and endIndex.
Example
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}