Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

Programming in Java

Lecture : Classes, Objects, Methods and Constructors

By
Arvind Kumar
Asst. Professor, LPU
Contents
• Class
• Object
• Methods
• Defining and adding variables
• Constructors
What is a class?
• A class can be defined as a template/ blue print that
describe the behaviors/states that object of its type
support.

• A class is the blueprint from which individual objects


are created.

• A class defines a new data type which can be used to


create objects of that type. Thus, a class is a template
for an object, and an object is an instance of a class.
• A class is declared by using class keyword.

class classname
{
type instance-variable1;
type instance-variable2;

type instance variable N;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
...
type methodnameN(parameter-list) {
// body of method
}
}
• The data, or variables, defined within a class are called
instance variables because each instance of the class (that
is, each object of the class) contains its own copy of these
variables.

• The code is contained within methods.

• The methods and variables defined within a class are


called members of the class.

• Java classes do not need to have a main( ) method till


JDK 1.6. We only specify one main() if that class is the
starting point for your program.
Defining Classes
 The basic syntax for a class definition:

class ClassName
{
[fields declaration]
[methods declaration]
}
 Bare bone class – no fields, no methods

public class Circle {


// my circle class
}
Object
• An object is an instance of the class which has well-defined
attributes and behaviors.
• Obtaining objects of a class is a two-step process.
• First, you must declare a variable of the class type. This variable
does not define an object. Instead, it is simply a variable that can
refer to an object.
• Second, you must acquire an actual physical copy of the object
and assign it to that variable. You can do this using the new
operator.
• Similar to variables we can define object of the class.
class_name Obj;
Obj= new class_name();

• It can be rewritten like


class_name Obj= new class_name();

• The new operator dynamically allocates memory for an object.


class var = new classname( );

• A class creates a logical framework that defines the


relationship between its members while An object has physical
reality. (That is, an object occupies space in memory.)
Method
• A method is a construct for grouping statements together
to perform a function.
• A method that returns a value is called a value retuning
method, and the method that does not return a value is
called void method.

• In some other languages, methods are referred to as


procedures or functions.
• A method which does not return any value is called a
procedure.
• A method which returns some value is called a function.
Methods
• A class with only data fields has no life. Objects created by such
a class cannot respond to any messages.
• Classes usually consist of two things: instance variables and
methods. General form of a method is:
type name(parameter-list)
{
// body of method
}
• 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;
Invoking Methods
• We've seen that once an object has been instantiated, we can use
the dot operator to invoke its methods

count = title.length()
• A method may return a value, which can be used in an
assignment or expression
• A method invocation can be thought of as asking an object to
perform a service
class Box
{ double width;
double height;
double depth;
double volume()
{ return width * height * depth;
} }
class BoxDemo4
{ public static void main(String args[])
{ Box mybox1 = new Box();
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
} }
Adding a Method That Takes Parameters
• While some methods don’t need parameters, most do.
Parameters allow a method to be generalized.
int square(int i)
{
return i * i;
}
• square( ) will return the square of whatever value it is called
with.
java.util.Scanner
• byte nextByte()
• short nextShort()
• int nextInt()
• long nextLong()
• float nextFloat()
• double nextDouble()
• String next()
• String nextLine()
Let’s Do It
• Create a class Student having attributes name, fatherName,
rollNo, section, college and address. Write a menu driven
program to enter and display the details of Students.
Brainstorming Questions
• class Demo
• {
• public static void main(String[] args) {
• int x = 5, y;
• while (++x < 7) {
• y = 2;
• }
• System.out.println(x + y);
• }
• }
• A) 7
• B) 8
• C) 9
• D) a compilation error

• Ans-D
Brainstorming Questions
• class Demo
• {
• public static void main(String... args) {
• System.out.println("JavaChamp");
• }
• }
• A) The program will compile and run fine printing JavaChamp as
output
• B) The program will compile fine but won't run correctly, a
NoSuchMethodError exception would be thrown
• C) There is a compilation error at declaring the main() argument,
should be an array of String instead
• D) Runtime error

• Ans-A
Let’s Do It
• Create a class named MyTriangle that contains the following
two methods:
//Return true if the sum of every two sides is greater than the third side.
public static boolean isValid( double side1, double side2,
double side3)
• //Return the area of the triangle.
public static double area( double side1, double side2, double
side3)
• Write a test program that takes three sides for a triangle as i/p
and computes the area if the input is valid. Otherwise, it
displays that the input is invalid.
Overloading Methods
• It is possible to define two or more methods within the same
class with same name and different signatures. The methods
are said to be overloaded, and the process is referred to as
method overloading.

• When an overloaded method is invoked, Java uses the type


and/or number of arguments as its guide to determine which
version of the overloaded method to actually call.

• Overloaded methods must differ in the type and/or number of


their parameters.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
}
Ambiguous Invocation
Sometimes there may be two or more possible matches
for an invocation of a method, but the compiler cannot
determine the most specific match. This is referred to
as ambiguous invocation. Ambiguous invocation is a
compilation error.

21
Constructors
• A constructor is a special method that is used to initialize a
newly created object.
• It has the same name as the class in which it resides and is
syntactically similar to a method.
• Once defined, the constructor is automatically called
immediately after the object is created, before the new
operator completes.
• It can be used to initialize the objects ,to required, or default
values at the time of object creation.
• It is not mandatory for the coder to write a constructor for the
class.
Default Constructor
• If no user defined constructor is provided for a class,
compiler initializes member variables to its default
values.
– numeric data types are set to 0
– char data types are set to null character(‘’)
– reference variables are set to null

• In order to create a Constructor observe the following


rules:
– It has the same name as the class
– It should  not return a value not even void
class Box
{ double width; double height; double depth;
Box() {width = 10; height = 10; depth = 10;}
double volume()
{ return width * height * depth;
} }
class BoxDemo4
{ public static void main(String args[])
{ Box mybox1 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
} }
Parameterized Constructors
class Box
{ double width; double height; double depth;
Box(double w, double h, double d) { width = w; height = h; depth = d;}
double volume()
{ return width * height * depth;
}}
class BoxDemo4
{ public static void main(String args[])
{ Box mybox1 = new Box(10, 20, 15);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
}}
Brainstorming Questions
• Can a constructor be declared static?

• Yes
• No

• Ans-No
Brainstorming Questions
• What are the legal modifiers which the constructor can be
declared with?

• A) public
• B) protected
• C) private
• D) final
• E) static
• F) abstract

• Ans-ABC
Brainstorming Questions
• public class Profile {
• private Profile(int w) { // line 1
• System.out.println(w);
• }
• public final Profile() { // line 5
• System.out.println(10);
• }
• public static void main(String args[]) {
• Profile obj = new Profile(50);
• }
• }
• A) Won't compile because of line (1) – constructor can't be private
• B) Won't compile because of line (5) – constructor can't be final
• C) 50
• D) 10 50

• Ans-B
Overloading Constructors
• In addition to overloading normal methods, you can also
overload constructor methods.

• In fact, for most real-world classes that you create, overloaded


constructors will be the norm, not the exception.
class A
{ int a,b;
public A(){ a=10;b=10;}
public A(int x){a=x; b=10;}
public A(int x, int y){a=x; b=y;}
public void display()
{System.out.println(“a= ”+a); System.out.println(“b= ”+b);}
public static void main(String a[])
{A x=new A(); x.display();
A y=new A(7); y.display();
A z=new A(6,8); z.display();
}}
Constructors Vs Methods
• Constructor name is class name. A constructors must
have the same name as the class its in.

• Default constructor. If you don't define a constructor for


a class, a default parameter-less constructor is
automatically created by the compiler.

• The default constructor initializes all instance variables to


default value (zero for numeric types, null for object
references, and false for booleans).
Static Initialization Blocks
• A static initialization block is a normal block of code enclosed
in braces, { }, and preceded by the static keyword.
example:
static
{
// whatever code is needed for initialization goes here
}
• A class can have any number of static initialization blocks, and
they can appear anywhere in the class body. The runtime
system guarantees that static initialization blocks are called in
the order that they appear in the source code.
Initializer blocks
• The Java compiler copies initializer blocks into every
constructor. Therefore, this approach can be used to share a
block of code between multiple constructors.

{
// whatever code is needed for initialization goes here
}
Using Objects as Parameters
class Test {
int a, b;
Test(int i, int j) {a = i;b = j;}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
ob1 == ob2: true
}
ob1 == ob3: false
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}}
The this Keyword

• Sometimes a method will need to refer to the object


that invoked it. To allow this, Java defines the this
keyword.
• this can be used inside any method to refer to the
current object. That is, this is always a reference to
the object on which the method was invoked.
class A
{ int a,b;
public A(int a, int b)
{
this.a = a;
a=a;
this.b = b;
b=b;
}
public void display()
{System.out.println(“a= ”+a); System.out.println(“b= ”+b);}
public static void main(String a[])
{A x=new A(6,9);
x.display();
}
}

0
0
Calling constructors from constructors
• When you write several constructors for a class, there
are times when you’d like to call one constructor
from another to avoid duplicating code.
• You can do this using the this keyword.
• In a constructor, the this keyword takes on a
different meaning when you give it an argument list:
it makes an explicit call to the constructor that
matches that argument list.
class A
{ int a,b;
public A(){ this(2,5); System.out.println(“Default”);}
public A(int x){this(x,5); System.out.println(“one arg”);}
public A(int a, int b){ this.a=a; this.b=b; System.out.println(“two
arg”);}
public void display()
{System.out.println(“a= ”+a); System.out.println(“b= ”+b);}
public static void main(String a[])
{A x=new A(); x.display();
A y=new A(7); y.display();
A z=new A(6,8); z.display();
}}
static
• A static method for the class can be called without
any object.
• static methods have the semantics of a global
function.
• Global functions are not permitted in Java, and
putting the static method inside a class allows it
access to other static methods and to static fields.
• You cannot call non-static methods from inside static
methods (although the reverse is possible).
Brainstorming Questions
• class Demo
• {
• static {
• int x = 3;
• }
• static int x;
• public static void main(String[] args) {
• x--; // line 7
• System.out.println(x);
• }
• }
• A) 3
• B) 2
• C) -1
• D) Compilation error at line 7, x is not initialized

• Ans-C
Garbage Collection
• Objects are dynamically allocated by using the new
operator
• Dynamically allocated objects must be manually
released by use of a delete operator.
• Java takes a different approach; it handles
deallocation automatically.
• The technique that accomplishes this is called
garbage collection.
• Garbage collection only occurs during the execution
of your program.
finalize()
• The finalize() method is declared in the java.lang.Object class.

• Before an object is garbage collected, the runtime system calls


its finalize() method.

• The intent is for finalize() to release system resources such as


open files or open sockets before getting collected.
Let’s Do It
Design a class named Account that contains:
• A private int data field named id for the account (default static counter).
• A private double data field named balance for the account (default 500Rs.).
• A private double data field named annualInterestRate that stores the current
interest rate (default 0). Assume all accounts have the same interest rate.
• A no-arg constructor that creates a default account.
• A constructor that creates an account with the specified id and initial
balance.
• The accessor and mutator methods for id, balance, and annualInterestRate.
• A method named getMonthlyInterest() that returns the monthly interest.
• A method named withdraw that withdraws a specified amount from the
account.
• A method named deposit that deposits a specified amount to the account.
• Write a menu driven Test program to use Account class.
Access Control
• public: A class, constructor, method or data field
visible to all the programs in any package.
• private: A class, constructor, method or data field
only visible to this class.
• protected: A class, constructor, method or data field
is visible in this package and sub class of this class in
any package.
• default: A class, constructor, method or data field
visible in this package.
Questions
Brainstorming Questions

You might also like