Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

1 Classes in JAVA

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

Classes in JAVA

INTRODUCTION TO JAVA PROGRAMMING

CSA6003T
BHAWANA BOTHARA
ASSISTANT PROFESSOR
Learning Objectives

1. Understand the concept and structure of a class in Java.


2. Learn how to create and use objects in Java.
3. Comprehend the principles of inheritance and polymorphism.
4. Gain knowledge of encapsulation and access modifiers.
5. Explore constructors and methods within Java classes.
Introduction

 The class is at the core of Java. It is the logical construct upon which the entire
Java language is built because it defines the shape and nature of an object. As
such, the class forms the basis for object-oriented programming in Java. Any
concept you wish to implement in a Java program must be encapsulated within a
class.
 A class in Java is a blueprint for creating objects. It defines a datatype by
bundling data and methods that operate on the data into one single unit.
 a class is a template for an object, and an object is an instance of a class.
Because an object is an instance of a class, you will often see the two words
object and instance used interchangeably
The General Form of a Class

class classname
{
type instance-variable1;
// ...
type instance-variableN;
public class ClassName
type methodname1(parameter-list)
{
{
// instance variables
// body of method
// constructors
}
// methods
// ...
}
type methodnameN(parameter-list)
{
// body of method
}
}
Classes in Java

 The data, or variables, defined within a class are called instance variables.
The code is contained within methods. Collectively, the methods and
variables defined within a class are called members of the class. In most
classes, the instance variables are acted upon and accessed by the methods
defined for that class. Thus, as a general rule, it is the methods that
determine how a class’ data can be used.
 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. Thus, the data for one object is separate and unique from
the data for another.
Java Objects
 An object in Java is a basic unit of Object-Oriented Programming and represents
real-life entities. Objects are the instances of a class that are created to use the
attributes and methods of a class.
 A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of :
 State: It is represented by attributes of an object. It also reflects the properties of an
object.
 Behavior: It is represented by the methods of an object. It also reflects the response
of an object with other objects.
 Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Example of an object: dog
Declaring Objects

o As just explained, when you create a class, you are creating a new data type.
You can use this type to declare objects of that type.
o However, obtaining objects of a class is a two-step process.
o 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.
o 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. The new operator
dynamically allocates (that is, allocates at run time) memory for an object and
returns a reference to it. This reference is, more or less, the address in memory of
the object allocated by new. This reference is then stored in the variable. Thus, in
Java, all class objects must be dynamically allocated
Using new keyword

ClassName objectName = new ClassName();


public class Dog
Example
{
String breed;
int age;

void bark()
{
System.out.println("Woof!");
}
}

public class TestDog


{
public static void main(String[] args)
{
Dog myDog = new Dog();
myDog.breed = "Bulldog";
myDog.age = 5;
myDog.bark();
}
}
How new works
Assigning Object Reference Variables
 Object reference variables act differently than you might expect when an
assignment takes place.

Box b1 = new Box();


Box b2 = b1;

 after this fragment executes, b1 and b2 will both refer to the same object. The
assignment of b1 to b2 did not allocate any memory or copy any part of the original
object. It simply makes b2 refer to the same object as does b1. Thus, any changes made
to the object through b2 will affect the object to which b1 is referring, since they are the
same object.
Method in Class
 This is the general form of a method:

type name(parameter-list) {
// body of method
}

 Here, type specifies the type of data returned by the method. 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 is specified by name. This can be any legal identifier
other than those already used by other items within the current scope.
 The parameter-list is a sequence of type and identifier pairs separated by
commas. Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called. If the method has no
parameters, then the parameter list will be empty.
 Methods that have a return type other than void return a value to the calling
routine using the following form of the return
Constructors
 it would be simpler and more concise to have all of the setup done at the
time the object is first created.
 Because the requirement for initialization is so common, Java allows objects
to initialize themselves when they are created. This automatic initialization is
performed through the use of a constructor.
 A constructor initializes an object immediately upon creation. 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 when the object is
created, before the new operator completes.
 Constructors look a little strange because they have no return type, not even
void.
 It is not necessary to write a constructor for a class. It is because the java
compiler creates a default constructor (constructor with no arguments) if
your class doesn’t have any.
Rules for creating Java constructor

 There are few rules defined for the constructor.


 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
Java Default Constructor
 A constructor is called "Default Constructor" when it doesn't have any
parameter.
 Syntax of default constructor:
class Bike1
{
//creating a default constructor
Bike1()
{
<class_name>() System.out.println("Bike is created");
{ }
} //main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
Java Parameterized Constructor

 A constructor which has a specific number of parameters is called a


parameterized constructor.
 Why use the parameterized constructor?
 The parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.
Copy Constructor

 Unlike other constructors copy constructor is passed with another object


which copies the data available from the passed object to the newly created
object.
 In Java,there is no such inbuilt copy constructor available like in other
programming languages such as C++, instead we can create our own copy
constructor by passing the object of the same class to the other
instance(object) of the class.
//Java program to initialize the values from one object to another object.
class Student6
{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Example of Parameterized Constructor
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Accessing Class Members
 Class members are the fields (variables) and methods defined inside a class.
These can be accessed through objects of the class.
public class Car
{
String model;
int year;
void displayDetails()
{
System.out.println("Model: " + model + ", Year: " +
year);
}
}
public class TestCar
{
public static void main(String[] args)
{
Car myCar = new Car();
myCar.model = "Tesla";
myCar.year = 2022;
myCar.displayDetails();
}
}
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. You can use this anywhere a reference to
an object of the current class’ type is permitted.
The finalize( ) Method

 Sometimes an object will need to perform some action when it is destroyed.


For example, if an object is holding some non-Java resource such as a file
handle or character font, then you might want to make sure these resources
are freed before an object is destroyed.
 To handle such situations, Java provides a mechanism called finalization. By
using finalization, you can define specific actions that will occur when an
object is just about to be reclaimed by the garbage collector.
Summary

 A class is a blueprint for creating objects.


 Objects are instances of classes.
 Class members (fields and methods) can be accessed using objects.
 Constructors are special methods used to initialize objects.
 Constructors can be default or parameterized.
Assessment
1. What is a class in Java?
A) A datatype
B) A blueprint for creating objects
C) A function
D) A variable
2. Which keyword is used to create an object?
A) class
B) new
C) create
D) object
3. Which method is called automatically when an object is created?
A) main
B) finalize
C) constructor
D) method
Assessment
4. The constructor of a class must have the same name as the ____. Class
5. In Java, the 'this' keyword is used to refer to ____. The current object
6. A default constructor is provided by the compiler if ____.
A) No constructors are defined
B) One parameterized constructor is defined
C) All methods are static
D) The class is abstract
7. An instance of a class is known as a ____. Object
8. What is the purpose of a constructor in Java? To initialize objects
Assignment

1. Explain the concept of classes and objects in Java with an example.


2. What are constructors in Java? Explain their types with examples.
3. What is the purpose of a default constructor?
4. How do you create and use objects in Java? Provide an example.
5. What is the significance of the 'this' keyword in Java? Provide an example.

You might also like