Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
FUNDAMENTAL PROGRAMMINGSTRUCTURE IN JAVA – CLASSES IN JAVA
7/23/2019
1P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
Basic Structure of a Simple Java program
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
2
Documentation Section
It includes the comments that improve thereadability of the program.
A comment is a non-executable statement thathelps to read and understand a programespecially when your programs get more complex.
It is simply a message that exists only for theprogrammer and is ignored by the compiler.
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
3
Java programming language supports three types of comments
Single line (or end-of line) comment Multiline Comment Documentation comments
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
4
Single line (or end-of line) comment
It starts with a double slash symbol (//) andterminates at the end of the current line.
The compiler ignores everything from// to theend of the line.
Example:// Calculate sum of two numbers
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
5
Multiline Comment
Java programmer can use C/C++ comment stylethat begins with delimiter /* and ends with */.
All the text written between the delimiter isignored by the compiler.
This style of comments can be used on part of aline, a whole line or more commonly to definemulti-line comment.
Example/*calculate sum of two numbers and it is a
multiline comment */7/23/2019
P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
6
Documentation comments
This comment style is new in Java. Such comments beginwith delimiter /** and end with */.
The compiler also ignores this type of comments just like itignores comments that use / * and */.
The main purpose of this type of comment is toautomatically generate program documentation.
The java doc tool reads these comments and uses them toprepare your program's documentation in HTML format.
Example/** The text enclosed here will be part of program
documentation */7/23/2019
P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
7
Package Statement
A package is a collection of classes, interfaces and sub-packages.
A sub package contains collection of classes,interfaces and sub-sub packages etc.
java.lang.*; package is imported by default andthis package is known as default package.
It must appear as the first statement in the sourcecode file before any class or interface declaration.
This statement is optional.
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
8
Import statements
Java contains many predefined classes that are stored into packages. In order to refer these standard predefined classes in your program,
you need to use fully qualified name (i.e. Packagename.className). But this is a very tedious task as one need to retype the package path
name along with the classname. So a better alternative is to use an import statement. An import statement is used for referring classes that are
declared in other packages.
The import statement is written after a package statement but beforeany class definition.
You can import a specific class or all the classes of the package.
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
9
Example for Import statements
To import Date class of java.util package using importstatement then write.
import java.util.Date; This statement allows the programmer to use the simple
classname Date rather than fully qualified classnamejava.util.Date in the code.Unlike package statement, youcan specify more than one import statement in yourprogram.
Example Import java.util.Date; /* imports only the Dateclass in java.util package */ import java.applet.*; //imports all the classes in java applet
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
10
Interface Section
An interface is similar to a class but contains onlyconstants and method declarations.
Interfaces cannot be instantiated. They can only be implemented by classes or
extended by other interfaces. It is an optional section and is used when we
wish to implement multiple inheritance feature inthe program.
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
11
Class Definition
Java program may contain multiple class definition.Classes are primary feature of Java program.
Exampleclass Addition{
void add(String args[]){int a=2, b=3, c;c=a+b;System.out.println(c);}
}7/23/2019
P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
12
Main Method Class Section
The Class section describes the information about user-defined classespresent in the program.
A class is a collection of fields (data variables) and methods thatoperate on the fields.
Every program in Java consists of at least one class, the one thatcontains the main method.
The main () method which is from where the execution of programactually starts and follow the statements in the order specified.
The main method can create objects, evaluate expressions, and invokeother methods and much more.
On reaching the end of main, the program terminates and controlpasses back to the operating system.
The class section is mandatory
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
13
Example
class HelloJava{
public static void main(String args[]){
System.out.println("Hello Java");}
}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
14
Example
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
15
Structure of Java Programs
class class-name {
public static void main(String args[]) {
statement1;
statement2;
…
…
}
}7/23/2019
P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
16
Structure of Java Programs
class keyword is used to declare a class in java. public keyword is an access modifier which
represents visibility, it means it is visible to all. static is a keyword, if we declare any method as static void is the return type of the method, it means it
doesn't return any value. main represents the starting point of the program. String[] args is used for command line argument.
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
17
Simple Program of Java
class Simple{
public static void main(String args[]){System.out.println("Hello Java");}
}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
18
Simple Program of Java
class Example2 {public static void main(String args[]) {int num; num = 100; System.out.println("This is num: " + num);num = num * 2;System.out.print("The value of num * 2 is ");System.out.println(num);}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
19
Classes in Java
7/23/2019
20
P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
Define Class
A class is a group of objects which have commonproperties.
It is a template or blueprint from which objectsare created.
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
21
Components of class declarations
Modifiers : A class can be public or has default access.
Class name: The name should begin with a initial letter.
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 surrounded by braces, { }.
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
22
Class in Java can contain
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
23
General Form of a Class
class classname {
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
} }
P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
24
7/23/2019
Instance Variable
A variable which is created inside the class butoutside the method is known as an instancevariable.
Instance variable doesn't get memory at compiletime.
It gets memory at runtime when an object orinstance is created.
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
25
Method in Java
A method is like a function which is used toexpose the behavior of an object.
Advantage of MethodCode ReusabilityCode Optimization
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
26
new keyword in Java
Used to allocate memory at runtime. All objects get memory in Heap memory area
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
27
Object and Class Example
class Student{//defining fieldsint id;//field or data member or instance variableString name;//creating main method inside the Student classpublic static void main(String args[]){//Creating an object or instanceStudent s1=new Student();//creating an object of Student//Printing values of the objectSystem.out.println(s1.id);//accessing member through reference variableSystem.out.println(s1.name);
}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
28
Main within class
Output0
null
Object and Class Example
class Student{int id;String name;}//Creating another class TestStudent1 which contains the main methodclass TestStudent1{public static void main(String args[]){Student s1=new Student();System.out.println(s1.id);System.out.println(s1.name);}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
29
Main outside class
3 Ways to initialize object
By reference variable By method By constructor
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
30
Initialization through reference
Initializing an object means storing data into the objectclass Student{int id;String name;}class TestStudent2{public static void main(String args[]){Student s1=new Student();s1.id=101;s1.name="Sonoo";System.out.println(s1.id+" "+s1.name);//printing members with a white space
}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
31
Output
101 Sonoo
Create multiple objects
class Student{int id;String name;}class TestStudent3{public static void main(String ar
gs[]){//Creating objectsStudent s1=new Student();Student s2=new Student();
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
32
//Initializing objectss1.id=101;s1.name="Sonoo";s2.id=102;s2.name="Amit";
//Printing dataSystem.out.println(s1.id+" "+s1.n
ame);System.out.println(s2.id+" "+s2.n
ame);}} Output
101 Sonoo 102 Amit
Initialization through method
class Student{int rollno;String name;void insertRecord(int r, String n){rollno=r;name=n;}void displayInformation(){System.o
ut.println(rollno+" "+name);}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
33
class TestStudent4{public static void main(String args[]){Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");s2.insertRecord(222,"Arya
n");s1.displayInformation();s2.displayInformation();}}
Initialization through a constructor
class Employee{int id;String name;float salary;void insert(int i, String n, float s) {
id=i;name=n;salary=s;
}void display(){System.out.println(id
+" "+name+" "+salary);}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
34
public class TestEmployee {public static void main(String[] args){
Employee e1=new Employee();Employee e2=new Employee();Employee e3=new Employee();e1.insert(101,"ajeet",45000);e2.insert(102,"irfan",25000);e3.insert(103,"nakul",55000);e1.display();e2.display();e3.display();
}}
101 ajeet 45000.0 102 irfan 25000.0 103 nakul 55000.0
Rectangle
class Rectangle{int length;int width;void insert(int l, int w){length=l;width=w;}void calculateArea(){System.out.pr
intln(length*width);}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
35
class TestRectangle1{public static void main(String args[]){Rectangle r1=new Rectangle();Rectangle r2=new Rectangle();r1.insert(11,5);r2.insert(3,15);r1.calculateArea();r2.calculateArea();
}}
55 45
Anonymous object
Anonymous simply means nameless. An object which has no reference is known as an
anonymous object. It can be used at the time of object creation only. Example:
new Calculation();
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
36
Calling method through a reference Calling method through an anonymous object
Calculation c=new Calculation();c.fact(5);
new Calculation().fact(5);
Example for Anonymous object
class Calculation{void fact(int n){int fact=1;for(int i=1;i<=n;i++){fact=fact*i;
}System.out.println("factorial is "+fact);}public static void main(String args[]){new Calculation().fact(5);//calling method with anonymous object}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
37
Factorial is 120
Creating multiple objects by one type only
Rectangle r1=new Rectangle(), r2=new Rectangle();
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
38
Creating multiple objects by one type only - Example
class Rectangle{int length;int width;void insert(int l,int w){length=l;width=w;}void calculateArea(){System.out.pri
ntln(length*width);}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
39
class TestRectangle2{public static void main(String args[]){Rectangle r1=new Rectangle(),r2=n
ew Rectangle();//creating two objectsr1.insert(11,5);r2.insert(3,15);r1.calculateArea();r2.calculateArea();
}}
55 45
Assignment
Write a java program to demonstrate the working of Bank System.
where we deposit and withdraw amount from our account. Create an Account class which has deposit() and withdraw
() methods method to check the balance of the account method to display the values of an object Create a test class to deposit and withdraw amount
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
40
Solution - Real Time Example
class Account{int acc_no;String name;float amount;//Method to initialize objectvoid insert(int a,String n,float amt){acc_no=a;name=n;amount=amt;}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
41
Contd..,
//deposit methodvoid deposit(float amt){amount=amount+amt;System.out.println(amt+" deposited");}//withdraw methodvoid withdraw(float amt){if(amount<amt){System.out.println("Insufficient Balance");}else{amount=amount-amt;System.out.println(amt+" withdrawn");}}
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
42
Contd..,
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}//Creating a test class to deposit
and withdraw amount
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
43
class TestAccount{public static void main(String[] args){Account a1=new Account();a1.insert(832345,"Ankit",1000);a1.display();a1.checkBalance();a1.deposit(40000);a1.checkBalance();a1.withdraw(15000);a1.checkBalance();}}
Reference
https://www.javatpoint.com/java-tutorial
http://nptel.ac.in/courses/106106147/
http://www.nptelvideos.com/java/java_video_lect
ures_tutorials.php
44
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
7/23/2019P.Poovizhi/CS8392/Fundamental programming structure in java – classes in java
45