0% found this document useful (0 votes)
3 views

Java Chapter 3

The document provides an overview of Java programming concepts, including classes, objects, methods, constructors, and keywords like 'this' and 'super'. It explains the structure and properties of Java classes, the nature of objects, and the functionality of methods, including method overloading and parameter passing. Additionally, it covers constructors and their types, as well as the use of command-line arguments in Java applications.

Uploaded by

adit669ya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Chapter 3

The document provides an overview of Java programming concepts, including classes, objects, methods, constructors, and keywords like 'this' and 'super'. It explains the structure and properties of Java classes, the nature of objects, and the functionality of methods, including method overloading and parameter passing. Additionally, it covers constructors and their types, as well as the use of command-line arguments in Java applications.

Uploaded by

adit669ya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Contents

 Java classes
 Java objects
 Java Methods
 Command Line Arguments
 Constructors
 this Keyword
 super Keyword
 static Keyword
 final Keyword
 Finally
 Java Comments
Java Classes
 A Java class is the template from which objects are created. It is a blueprint for an object. A class
is created using the keyword class.
 A class in Java is a set of objects which shares common characteristics/ behavior and common
properties/ attributes.
 It is a user-defined blueprint or prototype from which objects are created. For example, Student is
a class while a particular student named Ravi is an object.
 Properties of Java Classes:-
 Data memberClass is not a real-world entity. It is just a template or blueprint or prototype from
which objects are created.
 Class does not occupy memory.
 Class is a group of variables of different data types and a group of methods.
 A Class in Java can contain:
Method
Constructor
Nested Class
Interface
Java Classes
 Class Declaration in Java:-
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface; }
In general, class declarations can include these components, in order:
Modifiers: A class can be public or has default access.
Class keyword: class keyword is used to create a class.
Class name: The name should begin with an initial letter (capitalized by convention).
Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded
by the keyword implements. A class can implement more than one interface.
Body: The class body is surrounded by braces, { }.
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

Identity:- Name of Dog


Behavior:-Bark, Sleep, Eat
State:-Breed, Age, Color
Java Methods
 A method is a block of code which only runs when it is called. You can pass data, known as parameters, into
a method. Methods are used to perform certain actions, and they are also known as functions.
Syntax of Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body }
Advantage of Method
Code Reusability
Code Optimization
Method Declaration
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your application. In
Java, there 4 types of access specifiers.
public: It is accessible in all classes in your application.
protected: It is accessible within the class in which it is defined and in its subclasses.
private: It is accessible only within the class in which it is defined.
default: It is declared/defined without using any modifier. It is accessible within the same class and package within
which its class is defined. Note: It is Optional in syntax.
Java Methods
2.The return type: The data type of the value returned by the method or void if does not return a value. It
is Mandatory in syntax.
3. Method Name: the rules for field names apply to method names as well, but the convention is a little different. It
is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded by their data type, within the
enclosed parenthesis. If there are no parameters, you must use empty parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can throw; you can specify these exception(s). It
is Optional in syntax.
6. Method body: it is enclosed between braces. The code you need to be executed to perform your intended
operations. It is Optional in syntax.
Java Methods
 Types of Methods in Java:-There are two types of methods in Java:

1. Predefined Method:- In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any point.
2. User-defined Method:- The method written by the user or programmer is known as a user-defined
method. These methods are modified according to the requirement.

 Rules to Name a Method:


 While defining a method, remember that the method name must be a verb and start with
a lowercase letter.
 If the method name has more than two words, the first name must be a verb followed by an
adjective or noun.
 In the multi-word method name, the first letter of each word must be in uppercase except the first
word. For example, findSum, computeMax, setX, and getX.
Java Methods

With Return a Value With No Return a Value


class Test { class Test {
public static void main(String args []) { public static void main(String args []) {
int c = show(); Test t = new Test();
System.out.println(c); t.show();
} }
int show() { void show() {
int z = 10 + 20; int z = 10 + 20;
return z; System.out.println(z);
} }
} }
Output - 30 Output - 30
Java
Passing parameters by value:
Methods
 Passing Parameters by Value means calling a method with a parameter.
 The order of passing value in calling and called method should be
same. Passing Parameters by Value
class Test {
public static void main(String args []) {
int x = 10, y = 20;
Test t = new Test();
t.show(x, y);
}
void show(int x, int y) {
int z = x + y;
System.out.println(z);
}
}
Output - 30
Java
Method Overloading:
Methods
 If a class has more than one method with same name but different parameters is known as Method
Overloading.
 Passing Parameters by Value means calling a method with a parameter.
 There are ways to overload the method in java

 By changing the number of arguments


 By changing the data type
Java
Methods
By changing number of arguments By changing the data type
class Test { class Test {
void show(int x, int y) { int void show(int x, int y) { int z
z = x + y; = x + y;
System.out.println("z = System.out.println("z = "+z);
"+z); }
}
void show(int x, int y, double a)
void show(int x, int y, int a) { int
{ double c = x + y + a;
c = x + y + a;
System.out.println("c = "+c);
System.out.println("c = "+c);
} }
public static void main(String args []) { int public static void main(String args []) { int
x = 10, y = 20, a = 30; x = 10, y = 20; double a = 30.5; Test t =
Test t = new Test(); new Test();
t.show(x, y); t.show(x, y);
t.show(x, y, a); t.show(x, y, a);
} }
} }
Output – z = 30 Output – z = 30
c = 60
c = 60.5
Command Line
arguments
 At runtime, when you will want to pass any information into a program then this is accomplished by passing
command-Line arguments to main().
 They are stored as strings in the String array passed to main( ).
Command-Line Arguments
public class Test {
public static void main(String args[]) {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int sum = x+y;
System.out.println("sum: " + sum);
}
}

Execution Steps –
javac Test.java
java Test 10 20
Output – sum = 30
Constructor
s
 In java, Constructor is a special type of method. It is called at the time of object creation. Memory of
the object is allocated at the time calling constructor.
 Every class must have a constructor. If there is no constructor in class then java compiler automatically
creates a default constructor.

class Test { Compiler class Test {


} Test() { }
}

 It is used to initialize the object


 Constructor has no return type except current class instance.
 A constructor cannot be declared as final, static or synchronized.
 A class can have more than one constructor i.e., constructor can be
overloaded.
 Constructor has the same name as class name.
Constructor
s
 The default constructor is used to provide the default values to the object like zero (0), null, etc.,
depending on the data type.
class Test{
int id;
String name;
void display(){
System.out.pri
ntln(id+"
"+name);
}
public static void main(String args[]){
Test s1=new Test();
Test s2=new Test();

s1.display();
s2.display();
}
}

Output – 0 null
0 null
Constructor
s
 In java, there are three types of constructor:
 Parameterized Constructor
 Non – Parametrized Constructor
 Default Constructor

Parameterized and Non-Parameterized Constructor

A constructor has a specific parameter is called Parameterized Constructor. A constructor with no parameter is
called Non-Parameterized Constructor.
Constructor
Parameterized Constructor s Non-Parameterized Constructor

class Test{ class Test{


int id; int id;
String String name;
name; Test(){
Test(int i, String n){ id = 101;
id = i; name =
name = n; “Manish”;
} }
void show(){ void show()
System.out.println(" { System.out.println("Id =
Id = "+id+"\ "+id);
t"+"Name = System.out.println("Name =
"+name); "+name);
} }
public static void main(String args[]){ public static void main(String args[]){
Test t1=new Test(101, "Manish"); Test t1=new Test();
t1.show(); t1.show();
} }
} }

Output – Id = 101 Name = Output – Id = 101


Manish Name = Manish
Constructor
s
 In java, there are three types of constructor:
 Parameterized Constructor
 Non – Parametrized Constructor
 Default Constructor

Parameterized and Non-Parameterized Constructor

A constructor has a specific parameter is called Parameterized Constructor. A constructor with no parameter is
called Non-Parameterized Constructor.

Default Constructor

Constructor generated by compiler if there is no constructor in program, that constructor is known as Default
Constructor.
Constructor
Constructor Overloading
s
Constructor Overloading means that a class having more than one constructor with different parameter.
void show(){
Constructor Overloading
System.out.println("Id = "+id+"\t"+"Name = "+name);
class Demo{
}
int id, salary;
void show1(){
String name;
System.out.println("Id = "+id+"\t"+"Name = "+name+"\tSalary = "+salary);
Demo(int i,
String n){ }
public static void main(String args[]){
id = i;
Demo t=new Demo(101, "Manish");
name = n;
} Demo t1=new Demo(102, "Manish",
2000);
Demo(int i, String n, int sal){
t.show(); t1.show1();
id = i;
}}
name = n; salary = sal;
Output – Id = 101 Name =
}
Manish
Id = 102 Name = Manish Salary
= 2000
Constructor
Constructor Vs. Method
s
Java Constructor Java Method
A constructor is used to initialize the A method is used to expose the
state of an object. behavior of an object.

A constructor must not have a A method must have a return type.


return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a The method is not provided by the
default constructor if you don't compiler in any case.
have any constructor in a class.

The constructor name must be same The method name may or may not be same
as the class name. as the class name.
this
Keywords
 In java, this is a reference variable that refers to the current class object.
 this keyword is used to differentiate local and instance variable when both the variable name is same.

this (Reference Variable) object

 this() must be first statement in constructor.


 To reuse the constructor from constructor is known as Constructor Chaining.

Uses of this keyword

 this keyword is used to call current class method.


 this () is used to invoke current class constructor.
 this can be passed as an argument in method and constructor call.
this
this keyword Keywords
Used to call current class method

class Demo { class Demo


int id; { void show()
String name; {
Demo(int id, String name) { System.out.pr
this.id = id; intln("Hello
this.name = name; Show
} Method");
void show() { this.display();
System.out.println("ID = //
"+id+"\t Name = "+name); this.display()
} is same as
public static void main(String args[]) { display()
Demo d = new Demo(101, "Manish"); }
d.show(); void display()
{
}
System.out.pr
}
intln("Hi,
display
Output – Id = 101 Name = method");
Manish
}
public static void main(String args[]) {
Demo d = new Demo();
d.show();
}
this
Invoke current class constructor Keywords
To pass as an argument in the method

class Demo { class Demo {


Demo() { void show(Demo obj)
System.out.p { System.out.println("Method
rintln("Hello Invoked");
Mr. Abc"); }
} void display() {
Demo(int x) { show(this);
this(); }
System.out.pri public static void main(String args[]) {
ntln("x = Demo d = new Demo();
"+x); d.display();
} }}
public static void main(String args[]) {
Demo d = new Demo(20); Output – Method Invoked
}}

Output – Hello Mr. Abc


x = 20
this
Keywords
Actual Use of Constructor (Constructor Chaining) To prove this refer current class instance variable
class Demo {
int id, age; class Demo {
String name; void show()
Demo(int id, { System.out.println(this
String name) );
{ }
this.id = id; public static void
this.name = name; main(String args[]) {
} Demo d = new Demo();
Demo(int id, String name, int age) { System.out.println(d);
this(id, name); d.show();
this.age = age; }
} }
void display() {
System.out.println(id+"\t"+name+"\ Output – Demo@15db9742
t"+age); Demo@15db9742
}
public static void main(String args[])
{ Demo d = new Demo(101,"Manish");
Demo d1 = new Demo(102,"Vishal",30);
d.display();
d1.display();
}}
Output – 101 Manish 0
102 Vishal 30
Super
keyword
 The super keyword in java refers to the object of immediate parent class. It means that when you create an
object of subclass then an object of base class is created implicitly, which is referred by super reference
variable.
 The super keyword basically used in inheritance.
 super keyword is used to refer immediate parent class instance variable.
class Test
{ int age =
30;
}
class Demo extends Test {
int age = 20;
void show() {
System.out.println("Age in subclass = "+age);
System.out.println("Age in base class = "+super.age);
}
public static void main(String args[]) {
Demo d = new Demo();
d.show(); }}
Output - Age in subclass = 20
Age in base class = 30
Super
keyword
 super keyword is used to refer immediate parent class method whenever you define a method with same in
both the class i.e. Parent and child class both have same name method.
class Test
{ void display()
{
System.out.prin
tln("display in
base class");
}}
class Demo extends Test {
void display() {
System.out.println("displa
y in sub class");
}
void show()
{ super.display(
);
}
public static void main(String args[]) {
Demo d = new Demo();
d.show(); }}

Output - display in base class


Super
keyword
 super keyword can also be used to access the parent class constructor. super keyword can call both
parametric and non-parametric constructors depending on the situation.
class Test {
Test() {
System.out.
println("Ba
se Class
Constructor
");
}
}
class Demo extends Test {
Demo() {
super();
System.out.println("Sub
class Constructor");
}
public static void main(String args[]) {
Demo d = new Demo();
}}

Output - Base Class Constructor


Sub class Constructor
Super
Important Points about super keyword
keyword
 super() must be the first statement in subclass class constructor.
 If a constructor does not explicitly call a base class constructor, the Java compiler automatically inserts a call
to the non-argument constructor of the base class. If the base class does not have a non-argument constructor,
you will get a compile-time error. class Test {
Test() {
System.out.
println("Ba
se Class
Constructor
");
}}
class Demo extends Test {
Demo() {
System.out.println("Sub
class Constructor");
}
public static void main(String args[]) {
Demo d = new Demo();
}}

Output - Base Class Constructor


Sub class Constructor
static
keyword
 In java, static keyword is mainly used for memory management.
 In order to create a static member, you need to precede its declaration with the static keyword.
 static keyword is a non-access modifier and can be used for the following:
 static block
 static variable
 static method
 static class

Static Block - In java static block is used to initialize static data member and it is executed before the
method at the time of class loading.
main class Demo{
static {
System.out.println("Static Block");
}
public static void main(String args[]) { Output - Static Block
System.out.println("Main Method"); Main Method
}
}
static
Static Variable
keyword
 A variable declare with static keyword is called Static Variable.
 After declaration static variable, a single copy of the variable is created and divided among all objects at the
class level.
 Static variable can be created at class-level only and it gets memory only once in the class area at the time of
class loading.
 Static variable can’t re-initialized.

class Demo{ void show() {


int e_id; System.out.println("Emp_Id = "+e_id+"\t Emp_Name = "+name+"\t
String name; Company ="+company);
static String company = "PSIT"; }
Demo (int i, String n) { public static void main(String args[]) {
e_id = i; Demo d = new Demo(101, "Manish");
name = n; Demo d1 = new Demo(102, "Vishal");
} d.show();
Output - Emp_Id = 101 Emp_Name = Manish Company =PSIT
d1.show();
Emp_Id = 102 Emp_Name = Vishal Company =PSIT
}}
static
Static Variable keyword
static
Static Method
keyword
 A method declared with static keyword is known as static method.
 The most common example of static method is main() method.
 Static method can be invoked directly i.e. no need to create an object of a class. So static method can be
invoked with class.
 Static method can access static data member only.
 this and super can not be used in static context.
static
Static Method
keyword
Method call with class name Static data member can not access in static method

class Demo{ class


static int e_id = 101; Demo{ int
static String name = "Manish"; e_id = 101;
static void show() { static String name = "Manish";
System.out.println("Emp_Id = static void show() {
"+e_id+"\t Emp_Name System.out.println("Emp_Id =
= "+name); "+e_id+"\t Emp_Name
} = "+name);
public static void main(String args[]) { }
Demo.show(); public static void main(String args[]) {
} Demo.show();
} }
}
Output - Emp_Id = 101
Emp_Name = Manish Output – Compile Time Error
(non-static variable e_id cannot be
referenced from a
static context)
static
Static Class
keyword
 A nested class can be static. Nested static class doesn’t need a reference of outer
class.
 A static class cannot access non-static members of the outer class.
 You compile and run your nested class as usual that with outer class name.
Static class public static void main(String args[]) {
Demo.NestedClass dns = new
class Demo{ Demo.NestedClass();
static String name = "Manish"; dns.show(); }
static class NestedClass {
void show() { Output - Manish
System.out.println(" Emp_Name =
"+name);
}
}
final
keyword
 The final keyword is used to make a variable as constant. That is if you make a variable as final, you cannot
change the value of that variable.
 A final variable with no value is called blank final variable. Blank final variable can be initialized in the
constructor only.
 Final keyword can be applied with following:

Variable - If you declare a variable with final keyword then it must be initialized.
Final Variable Final Variable (Can’t change value)
class Demo class Demo
{ final int x = { final int x =
10; void show() 10; void show()
{ { x = 20;
System.out.prin System.out.prin
tln(x); tln(x);
} }
public static void main(String args[]) { public static void main(String args[]) {
Demo d = new Demo(); Demo d = new Demo();
d.show(); d.show();
}} }}
Output - 10 Output - error: cannot assign a value
to final variable x
final
Method - If you declare a method as final itkeyword
means that you cannot override (Discuss in Inheritance) this
method.
Final Method Cannot Override

class Test {
final void show()
{ System.out.println("Parent Class
Method");
}
}
class Demo extends Test{
void show(){
System.out.println("Cannot override due to final method.");}
public static void main(String args[]) {
Demo d = new Demo();
d.show();
}
}

Output - error: show()


in Demo cannot
override show() in Test
(Compile Time Error)
final
keyword
Class - If you declare a class as final it means that you cannot inherit (Discuss in Inheritance) this class. That
is,
you cannot use extends keyword.
Final Class cannot inherited

final class Test {}


class Demo extends Test{
void show(){
System.out.println("Cann
ot override due to final
method.");
}
public static void main(String args[]) {
Demo d = new Demo();
d.show();
}
}

Output - error: cannot inherit from


final Test
Note – Constructor cannot be declared as final because it is never inherited.
Finally
In java finally is a block that is used to execute important code such as closing connection, etc. Finally block is
always executed whether exception is handled or not.

Note – As finally used in Exception so it will be discussed later in Exception chapter.

finally {
// Statements;
}
Java
 The Java comments are the statements inComments
a program that are not executed by the compiler and
interpreter.
 Comments are used to make the program more readable by adding the details of the code.
 It makes easy to maintain the code and to find the errors easily.
 The comments can be used to provide information or explanation about the variable, method, class,
or any statement.
 It can also be used to prevent the execution of program code while testing the alternative code.

Types of Java Comments:- There are three types of comments in Java.


 Single Line Comment
 Multi Line Comment
 Documentation Comment
Java
1) Java Single Line Comment
Comments
The single-line comment is used to comment only one line of the code. It is the widely used and easiest way
of commenting the statements. Single line comments starts with two forward slashes (//). Any text in front
of // is not executed by Java.

2) Java Multi Line Comment


The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex
code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line
comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java.
3) Java Documentation Comment

Documentation comments are usually used to write large programs for a project or software application as it
helps to create documentation API. These APIs are needed for reference, i.e., which classes, methods,
arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are placed
between /** and */.

You might also like