Java Class
Java Class
Class
A class is a template or a prototype that defines a type of object. A class
is to an object what a blue print is to properties of an house. Any no of
houses can be constructed from a single blue print. In a similar way many
objects can be constructed from a single class. A class outlines the
properties of an object. Objects created from the same class show similar
characteristics. public class mainClass
Declaring Classes:- { public static void main(String s[])
{
class A A ob1;
{ ob1=new A();
char c; ob1.method1();
int i; ob1.method2();
double d; A ob2=new A();
void method1() ob2.method1();
{ System.out.println (“Hello”); } ob2.method2();
void method2() } }
{System.out.println(“Welcome”); }
} Output:-Hello
welcome
Hello
Welcome
Class
The new Operator:- new operator is used to create instance of class (i.e, object).
A ob1; It simply states what type of object
ob1=new A(); variable ob1 will be.
ob1.method1();
ob1.method2(); Object is actually created when the new
operator is called.
A ob2=new A();
ob2.method1(); Object ob1 calls method1().
ob2.method2();
} } Object ob2 here is declared & created at
a time.
Java Program to Initialize Member Variables using
Method
class Book public class bookdemo
{ {
String title; public static void main(String s[])
String author;
{
double price;
void input(String tn, String an, double p) Book obj=new Book();
{ obj.input(“Java”, “Guruswamy",560.80);
title=tn; obj.display();
author=an; }
price=p; }
}
void display()
{
System.out.println("Title of the book:"+title); Output:-
System.out.println("Author of the Title of the book: Java
book:"+author); Author of the book: Guruswamy
System.out.println("Price of the book:"+price); Price of the book: 560.80
}
}
Constructor
Constructors are special kind of member functions that are used to
initialized objects at the time of creation.
Constructors allows us to perform initialization of member variables &
perform any other operations we want to perform( like allocating member
blocks, opening files etc.) when an object is created from a class.
They are invoked/called automatically when the objects are created.
Constructors are always given the same name as that of the class.
Constructors do not have a return type not even void
They are called constructors because they construct the values of data
members of the class.
Constructors can be i)Default constructor , ii)Argumented or
parameterized constructor, iii)Copy constructor (special type of
argumented constructor which takes reference to an object as argument or
parameter.)
Using member functions we can initialize the member variables of a class
but these functions cannot be used to initialize the member variables at
the time of creation of their objects.
Java Program to Initialize Member Variables using
Constructor
class Book public class bookdemo
{ {
String title; public static void main(String s[])
String author;
{
double price;
Book(String tn, String an, double p) Book obj=new Book(“C”, “swamy",560);
{ obj.display();
title=tn; }
author=an; }
price=p;
}
void display()
{
System.out.println("Title of the book:"+title); Output:-
System.out.println("Author of the Title of the book: C
book:"+author); Author of the book: swamy
System.out.println("Price of the book:"+price); Price of the book: 560
}
}
Java Program Illustrating Class Constructors
public class A void method1()
{ public static void main(String s[]) {
{ System.out.println(“Welcome”);
B ob1=new B();
}
B ob2=new B(‘b’,20,200.8);
System.out.println(“ob1.c”:+ob1.c);
void method2()
System.out.println(“ob1.i”:+ob1.i); {
System.out.println(“ob1.d”:+ob1.d); System.out.println(“Hello”);
System.out.println(“ob2.c”:+ob2.c); }
System.out.println(“ob2.i”:+ob2.i); }
System.out.println(“ob2.d”:+ob2.d);
ob1.method1(); ob1.method2(); }
} Output:-
class B b1.c=a
{ b1.i=10
char c; b1.d==100.4
int i;
b2.c=b
double d;
B() // default constructor b2.i=20
{ c=‘a’; i=10; d=100.4; } b2.d==200.8
B( char cc, int ii, double dd) Welcome
//parameterised constructor Hello
{ c=cc; i=ii; d=dd; }
Difference between Constructor & Method
Constructor Method
1) It has the same name as the class itself. 1) It has its own name because it is an
2) Constructor has no return type. ordinary member function of a class.
3) Constructor are invoked or called by the 2) Method have return type which may be
new operator. void.
4) Syntax:- 3) Method is invoked or called using the dot
[modifier]<classname>(parameter list) operator.
{ 4) Syntax:-
//body of the constructor; [access specifier][modifier]<return
} type><methodname>(parameter list)
For e.g, {
B(char aa, int ii, double dd ) //body of the method;
{ c=aa; i=ii; d=dd; } }
For e.g,
void input(char aa, int ii, double dd )
{ c=aa; i=ii; d=dd; }
Overloading Method
class E public class A
{ {
void method() public static void main(String s[])
{ {
System.out.println(“Hello”); E ob1=new E();
} ob1.method();
void method(int i) ob1.method(10);
{ ob1.method(10.99);
System.out.println(“Hi”); ob1.method(12,89.99);
} //ob1.method(12.88,99);
void method(int i,float f)
{ }
System.out.println(“Welcome”); }
}
void method(float f)
{
Output:-
System.out.println(“Good”);
} Hello
Hi
} Good
Welcome
Overloading Constructors
In addition to overloading normal methods, we can also overload constructor.
class Box double vol()
{ {
double width; return width*height*depth;
double height; }
double depth; public static void main(String s[])
Box() //default constructor {
{ width=height=depth=0.0; Box ob1=new Box(10.0,20.0,30.0);
} Box ob2=new Box();
//parameterized constructor Box ob3=new Box(6.0);
Box(double w, double h, double d) Box ob4=new Box(ob1);
{ width=w; System.out.println(“Volume of ob1”:+ob1.vol());
height=h; System.out.println(“Volume of ob2”:+ob2.vol());
depth=d; } System.out.println(“Volume of ob3”:+ob3.vol());
//parameterized constructor System.out.println(“Volume of ob4”:+ob4.vol());
Box(double l) }
{ width=height=depth=l; }
} Output:-
Box(Box ob) //copy constructor
Volume of ob1:600
{ width=ob.width;
height=ob.height; Volume of ob2: 0
depth=ob.depth; Volume of ob3:216
Volume of ob4:600
this Keyword
Sometimes a method will need to refer to the object that invoke it. To allow
this, Java uses “this” keyword. “this” 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. “this” will always refer to the invoking object. In
Java it is not possible to declare 2 local variable with the same name inside a
class. But we can have local variable & instance variable with same name. So
the local variables hides the instance variable. In this situation we can use
“this” keyword to indicate instance variable.
finalize() Method:- Sometimes an object will need to perform some action when it is
destroyed. For e.g, if an object is holding some non-java resources such as a file
handle or window character font, then we have to free these resources before an
object is destroyed. To handle such situations, Java provides a mechanism called
finalization.
protected void finalize()
{ //finalization code here
}
Java objects are destroyed during garbage collection. finalize is thus called when java
performs garbage collection.
Access Specifier & Modifier
Access Specifier:-
1) public
2) private
3) protected
4) default
Modifier:-
1) final
2) native
3) transient
4) synchronized
5) volatile
6) static
Static Modifier
• The static modifier specifies that a variable or a method is the same for all
objects of a particular class. The space for static variable is shared by all
subsequent objects. Static method is one whose implementation is the same for
all objects.
• Static method have several restrictions-
1. They can only call other static methods directly.
2. They must only access static data.
3. They cannot refer to this or super in any way.
• If we need to do computation in order to initialize our static variables we can
declare a static block which gets executed exactly once, when the class is first
loaded and executed before main.
• Outside of the class in which they are defined, static methods & variables can be
used independent of any object. To do so, we need only specify the name of their
class followed by dot operator.
• Advantage of static method is that they can be accessed without having to create
an object of the class.
• The most common example of static member is main(). main() is declared as
static because it must be called before any objects exist.
• Static block execution without main method is only supported in Java versions
Example of Static Data Member, Method & Block and their access within the class
class A{ Output:-
static int a=3; static block
static int b; Main Block
static void method(int x) { x=5667
System.out.println(“x=”+x); a=3
System.out.println(“a=”+a); b=12
System.out.println(“b=”+b); }
static {
System.out.println(“static block”);
b=a*4; }
public static void main(String s[])
{
System.out.println(“Main Block”);
method(5667);
}
}
Example of Accessing Static Data Member & Method from
Outside The Class
class A{ Output:-
static int a=3; nonstatic
static int b=99; a=3
static void callme() { b=99
System.out.println(“a=”+a); }
void f1() {
System.out.println(“nonstatic”); }
}
public class B
{
public static void main(String s[])
{
A ob1=ne A();
ob1.f1();
A.callme();
System.out.println(“b=”+A.b);
}
}
Final Modifier
• The final modifier can be used in data member or variable, in method or in class.
1. If data member is final then that can be treated as constant i.e whose value can not be
changed. Syntax:- final public int a=100;
2. If method is final that method can not be overridden in child or sub class. Syntax:- final
public void method1() { }.
3. If class is final that can not be inherited. Syntax:- final class A { }.
Native Modifier
• The native modifier informs the java compiler that a method’s implementation is in an
external c file.
• The method declaration ends with a semicolon. There are no curly braces containing java
code. This is implemented in c or c++ code.
Transient Modifier
• Object has a transient part which means it is not part of the persistent state of an
object. We can use this modifier if we do not want to store certain data member
to file. It is used only with data member.
class Trans
{ transient boolean d; //not to be stored
int a; // to be stored }
Synchronized Modifier
It is used in multi-threaded programming.
Native Modifier
It may be modified by asynchronous threads. This modifier is used for variable that can be
simultaneously modified by many threads.
Note::-- We can change the order of access specifier & modifiers like
public static void main(String s[])
or
static public void main(String s[])
We can not use 2 or more access specifier in a declaration like
private public int a; -----> This is invalid
Nested & Inner Class
• Inner class means class within another class.
• Inner classes can not have static declaration of method but
it can be static if the class itself is static.
class A{
int x=100;
void test() {
C i=new C();
i.display(); }
class C
{ void display() {
System.out.println(“x=”+x); }
}
public class B
{
public static void main(String s[])
{
A ob1=new A();
ob1.test();
}
}
Output: x=100
Nested & Inner Class
• Inner class can be defined within a for loop.
• After compilation of the following program 3 class file (byte code) will be created-
A.class, B.class, A$Inner.class. class A{
int x=100;
void test() {
for(int i=0; i<10; i++) {
class Inner{
void display() {
System.out.println(“x=”+x); } }
Inner i=new Inner();
i.display(); }
}
}
public class B
{
public static void main(String s[])
{
A ob1=new A();
ob1.test();
}
}
Output: x=100
Few points of String Class
String m=”this is a test”; class s{
System.out.println(m); ----> this is a test public static void main(String s[])
{
String m=”I”+”like”+”java”;
String s1=”First String”;
System.out.println(m); ----> I like Java String s2=”Second String”;
Few Methods in String Class:- String s3=s1;
• boolean equals(String object) System.out.println(“length of s1=”+s1.length());
System.out.println(“index at 3=”+s1.charAt(3));
• int length() if(s1.equals(s2))
• char charAt(int index) System.out.println(“s1=s2”);
else
// String Array:- System.out.println(“s1!=s2”);
class A{ if(s1.equals(s3))
public static void main(String s[]) System.out.println(“s1=s3”);
{ else
String str[]={“one”,”two”,”three”}; System.out.println(“s1!=s3”);
for(int i=0;i<str.length;i++) }
System.out.println(str[i]); }
} output-> lengthof s1=12
} index at 3=s
s1!=s2
S1=s3
Command Line Arguments
We can pass information into a program when we run it. This is accomplished by
passing command line arguments to main(). These are stored as string array passed
to main().
For e.g->
class A{
public static void main(String s[])
{
for(int i=0;i<s.length;i++)
System.out.println(s[i]);
}
}
Execution:-
java A aa abcd cder werr ->running A.class with passing 4 command line arguments
Output:-
aa
abcd
cder
werr
Inheritance
Reusability is another important feature of OOP. Reusability of code can be
implemented using Inheritance. Inheritance means acquiring properties from some
high level versions. That is, the mechanism of deriving a new class from an old one is
called inheritance or derivation. The old class is referred to as the base class or super
class or parent class & the new one is called the derived class or sub class or child
class.
Parent The derived class inherits some or all of the traits from
Class
the base class.
Child
Class
Types of Inheritance:-
Inheritance
Derived Class
Derived Class
Types of Inheritance
Multilevel Inheritance:- When one derived class is inherited by another
derived class, then it is called multiple inheritance.
Base Class
Intermediate
Derived Class
Derived Class
Base Class
Base Class
Derived Class3
Example of Single Inheritance (with variables of default access specifier)
class A{
int i, j;
void setij(int x, int y)
{ i=x; j=y;
}
}
class B extends A
{
int t;
void sum()
{ t=i+j; }
}
public class C {
public static void main(String s[])
{
B b1=new B();
b1.setij(10,12);
b1.sum();
System.out.println(“b1.t=”+b1.t);
}
}
Example of Single Inheritance (with variables of private access specifier)
class A{
int i;
private int j;
void setij(int x, int y)
{ i=x; j=y;
}
}
class B extends A
{
int t;
void sum()
{ t=i+j; // ERROR as j is not
//accessible here}
}
public class C {
public static void main(String s[])
{
B b1=new B();
b1.setij(10,12);
b1.sum();
System.out.println(“b1.t=”+b1.t);
} }
Use of Super Keyword
Super has two general forms. 1st one is to call the superclass constructor. The 2nd
one is to access a member of the superclass that has been hidden by a member of a
subclass.
A)Using super to call super class constructors:-
class Box{ Thus super() always refer to the
private int w, h, d; super class immediately above the
Box(int w1,int h1, int d1) calling class. This is true even in a
{ w=w1; h=h1; d=d1; } multileveled hierarchy. super()
int vol() must be always first statement
{ return w*h*d; }
executed inside a subclass
}
class B extends Box constructor.
{ int we;
B(int x, int y, int z, int m)
{
super(x,y,z); we=m;
}
public class C {
public static void main(String s[])
{
B b1=new B(10, 20, 30, 40);
System.out.println(“Volumn=”+b1.vol());
Use of Super Keyword
B)Using super to access member variable of super class:-
class A{ This situation is most applicable in
int i; which member names of a subclass
} hide members by the same name
class B extends A in the super class.
{ int i; //This i hides the i in A
B(int x, int y)
{
super.i=x; i=y;
}
void show() Output:-
{ i in A=10 i in B=20
System.out.println(“i in A=“+ super.i+” i in
B=“+ i); }
}
public class C {
public static void main(String s[])
{
B b1=new B(10, 20);
b1.show();
} }
Use of Super Keyword
C)Using super to access member function of super class:-
class A{ This situation is most applicable in
int i; which method name of a subclass
A(int x) hides method by the same name in
{ i=x; } the super class.
void show()
{ System.out.println(“i=“+i); }
}
class B extends A
{ int j;
B(int x, int y) Output:-
{ super(x); j=y; i =10
} k=20
void show()
{ super.show();
System.out.println(“k=“+ k);
} }
public class C {
public static void main(String s[])
{
B b1=new B(10, 20);
b1.show();
Order of Constructors Calling in
Multilevel Inheritance
class A{
A()
{ System.out.println(“A Constructor”); }
}
class B extends A
{
B()
{ System.out.println(“B Constructor”); }
}
class C extends B Output:-
{ A Constructor
C() B Constructor
{ System.out.println(“C Constructor”); } C Constructor
}
public class D {
public static void main(String s[])
{
C c1=new C();
}
}
Dynamic Method Dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden
function is resolved at runtime, rather than compile time. It is important because
this is how Java implements run time polymorphism.
class A{ C c1=new C();
void callme() A r; Output:-
{ System.out.println(“Inside A”); } r=a1; Inside A
} r.callme(); Inside B
class B extends A r=b1; Inside C
{ r.callme();
void callme() r=c1;
{ System.out.println(“Inside B”); } r.callme();
} }
class C extends B }
{
void callme() The version of callme() executed is
{ System.out.println(“Inside C”); } determined by the type of object being
} referred to at the time of the call. Had it
public class D { been determined by the type of the
public static void main(String s[]) reference variable r, we would see 3 calls
{ to A’s callme() method.
A a1=new A();
B b1=new B();
Abstract Class
Abstract classes are classes that are partially implemented. Abstract methods are
methods that are declared but not implemented. Any class that contains one or
more abstract methods must also be declared as abstract. There can be no objects
of an abstract class. That is, abstract class can not be directly instantiated with the
new operator. We cannot declare abstract constructors, abstract static method,
abstract private method. Any subclass of an abstract class must either implements
all of the abstract methods in the super class or be itself declared as abstract.
abstract class A{ b1.callme();
abstract void callme(); b1.call();
void call() }
{ }
{ System.out.println(“Concrete method”); }
}
class B extends A
{
callme()
{ System.out.println(“B Implemented”); }
}
public class D {
public static void main(String s[]) {
B b1=new B();
Difference between Abstract & Concrete Class
Abstract Class Concrete Class
1. Some or all methods are not 1. Specifies the full set of method for an
implemented. object.
2. Can not have instance. 2. It has instance.
3. Must have sub class where it’s abstract 3. It has sub class.
methods are defined. 4. It can have constructor.
4. We can not declare abstract constructor
or abstract static methods.
Difference between Overloading & Overriding
Overloading Overriding
1. It means that 2 or more methods use 1. Overriding occurs when a subclass
the same name with different method & super class method use the
parameter list. Such both methods are same name with identical signature
in the same class. such that subclass hide the super class
2. This is relationship between methods in method.
a same class. 2. This is relationship between super class
3. May have different datatype. method & a sub class method.
4. Does not hide inheritance from the 3. May have same return type.
super class. 4. Hide inheritance from the super class.
5. Different method signature. 5. Same method signature, otherwise it
6. Static binding, it depends on the type of will produce compile time error.
object variable. 6. Dynamic binding, it depends on the type
7. This is an e.g. of compile time of the actual object at runtime.
polymorphism. 7. This is an e.g for runtime polymorphism.
8. Overload method may be any no. of 8. Subclass method overriden at most
times. once in any one of the sub class.
9. Super class method share the same 9. Sub class method replace the super
name. class method.
Thank You