Professional Documents
Culture Documents
In the early 1990's, putting intelligence into home appliances was thought to be the
next "hot" technology.
Examples of intelligent home appliances:
Coffee pots and lights that can be controlled by a computer's programs.
Televisions that can be controlled by an interactive television device's programs.
Anticipating a strong market for such things, Sun Microsystems in 1991 funded a
research project (code named Green) whose goal was to develop software for
intelligent home appliances.
An intelligent home appliance's intelligence comes from its embedded processor chips
and the software that runs on the processor chips.
To handle the frequent turnover of new chips, appliance software must be extremely
portable.
Originally, Sun planned to use C++ for its home appliance software, but they soon
realized that C++ was less than ideal because it wasn't portable enough and it relied
too heavily on hard-to-maintain things called pointers.
Thus, rather than write C++ software and fight C++'s inherent deficiencies, Sun
decided to develop a whole new programming language to handle its home appliance
software needs.
Their new language was originally named Oak (for the tree that was outside project
leader James Gosling's window), but it was soon changed to Java.
When the home appliance software work dried up, Java almost died before being
released.
Fortunately for Java, the World Wide Web exploded in popularity and Sun realized it
could capitalize on that.
Web pages have to be very portable because they can be downloaded onto any type of
computer.
What's the standard language used for Web pages?
Java programs are very portable and they're better than HTML in terms of providing
user interaction capabilities.
Java programs that are embedded in Web pages are called applets.
Although applets still play a significant role in Java's current success, some of the
other types of Java programs have surpassed applets in terms of popularity.
In this course, we cover Standard Edition (SE) Java applications. They are Java
programs that run on a standard computer – a desktop or a laptop, without the need
of the Internet.
Because the world is made from distinct objects, which consist of other
objects, etc., and this is often a natural and powerful way of
representing a situation or problem.
STATE BEHAVIOUR
• Name • Sleeps a lot
• Breed • Scratches
• Weight furniture
• Age • Catches mice
• Asleep • Fights other cats
Examples of OO languages
C++
Classic example uses C syntax
Java
Based on C++, often used for Web and graphics
Visual Basic, Visual C++
Windows programming
Implementation of objects
Behaviour controlled by
method functions or
BEHAVIOUR subroutines which act on the
local variables and interface
with the outside.
J Advantage
Objects provide a powerful and natural approach for representing many problems.
Features such as inheritance allow already written objects to be re-used – program
modification in OOP’s is comparatively easier. OOP’s Paradigm (Abstraction,
Encapsulation, data hiding, Inheritance, Polymorphism)
L Disadvantages
Certainly more difficult than conventional programming some concepts are relatively
hard, even for experienced programmers Implementation of objects often use
complicated syntax/semantics OOP is comparatively not famous for efficiency
(memory or execution time).
Why Java?
It’s the current “hot” language
It’s almost entirely object-oriented
It has a vast library of predefined objects and operations
Its more platforms independent.
This makes it great for Web programming
It’s more secure
It isn’t C++
OOP Paradigm
Java is a full object oriented language, all code has to go into classes.
Making Objects interact: Creating objects from abstract data types and
defining their relationships.
Because the Java VM is available on many different operating systems, the same .class
files are capable of running on Microsoft Windows, the Solaris Operating System (Solaris
OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine,
perform additional steps at runtime to give your application a performance boost. This
includes various tasks such as finding performance bottlenecks and recompiling (to native
code) frequently used sections of code.
Through the JVM, the same application is capable of running on multiple platforms.
First Java program:
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello, world!");
}
} // end class Hello
All Java programs must be enclosed in a class. Think of a class as the name of the
program.
The name of the Java program's file must match the name of the Java program's class
(except that the filename has a .java extension added to it).
Proper style dictates that class names start with an uppercase first letter.
Since Java is case-sensitive, that means the filename should also start with an uppercase
first letter.
Case-sensitive means that the Java compiler does distinguish between lowercase and
uppercase letters.
In the Java programming language, every application must contain a main method whose
signature is:
Memorize (and always use) public class prior to your class name. For example:
public class Hello
Inside your class, you must include one or more methods.
A method is a group of instructions that solves one task. Later on, we'll have larger
programs and they'll require multiple methods because they'll solve multiple tasks. But
for now, we'll work with small programs that need only one method - the main method.
Memorize (and always use) this main method heading:
public static void main(String[] args)
When a program starts, the computer looks for the main method and begins execution
with the first statement after the main method heading.
Braces
Use braces, { }, to group things together.
For example, in the Hello World program, the top and bottom braces group the
contents of the entire class, and the interior braces group the contents of the main
method.
Proper style dictates:
Place an opening brace on a line by itself in the same column as the first character of the
previous line.
Place a closing brace on a line by itself in the same column as the opening brace.
System.out.print
To create a Java program that can be run on a computer, submit your Java source code
to a compiler. We say that the compiler compiles the source code. In compiling the
source code, the compiler generates a bytecode program that can be run by the
computer's JVM (Java Virtual Machine).
Java source code filename = <class-name> + .java
Java bytecode filename = <class-name> + .class
Identifiers
Identifier = the technical term for a name in a programming language
Identifier examples –
class name identifier: Hello
method name identifier: main
variable name identifier: height
Identifier naming rules:
Must consist entirely of letters, digits, dollar signs ($), and/or underscore (_) characters.
The first character must not be a digit.
If these rules are broken, your program won't compile.
If these rules are broken, it won't affect your program's ability to compile, but your
program will be harder to understand and you'll lose style points on your homework.
Use letters and digits only, not $'s or _'s.
All letters must be lowercase except the first letter in the second, third, etc. words. For
example:
firstName, x, daysInMonth
Addendum to the above rule – for class names, the first letter in every word (even the
first word) must be lowercase. For example:
StudentRecord, WorkShiftSchedule
Names must be descriptive.
Variables
A variable can hold only one type of data. For example, an integer variable can hold
only integers, a string variable can hold only strings, etc.
How does the computer know which type of data a particular variable can hold?
Before a variable is used, its type must be declared in a declaration statement.
Declaration statement syntax:
<type> <list of variables separated by commas>;
Example declarations:
String firstName; // student's first name
String lastName; // student's last name
int studentId;
int row, col;
Assignment Statements
Java uses the single equal sign (=) for assignment statements.
In the below code fragment, the first assignment statement assigns the value 50000 into
the variable salary.
int salary;
String bonusMessage;
salary = 50000; Commas are not allowed in
numbers.
bonusMessage = "Bonus = $" + (.02 * salary);
string concatenation
Note the + operator in the second assignment statement. If a + operator appears
between a string and something else (e.g., a number or another string), then the +
operator performs string concatenation. That means that the JVM appends the item at
the right of the + to the item at the left of the +, forming a new string.
Constants
Program Template
Import java.io.*;
public class Test
{
public static void main(String [ ] args)
{
<method-body>
}
} // end class Test
Initialization Statements
Initialization statement:
Initialization statement is use to assign a value to a variable as part of the variable's
declaration.
Initialization statement syntax:
<type> <variable> = <value>;
Example initializations:
int totalScore = 0; // sum of all bowling scores
int maxScore = 300; // default maximum bowling score
Example initializations (repeated from previous slide):
int totalScore = 0; // sum of all bowling scores
int maxScore = 300; // default maximum bowling score
Here's an alternative way to do the same thing using declaration and assignment
statements (instead of using initialization statements):
int totalScore; // sum of all bowling scores
int maxScore; // default maximum bowling score
totalScore = 0;
maxScore = 300;
It's OK to use either technique and you'll see it done both ways in the real world.
The Java programming language is strongly typed, which means that all variables must first
be declared before they can be used. This involves stating the variable's type and name, as
you've already seen:
int gear = 1;
Doing so tells your program that a field named "gear" exists, holds numerical data, and has
an initial value of "1". A variable's data type determines the values it may contain, plus the
operations that may be performed on it. In addition to int, the Java programming language
supports seven other primitive data types. A primitive type is predefined by the language
and is named by a reserved keyword. Primitive values do not share state with other
primitive values. The eight primitive data types supported by the Java programming
language are:
Short The short data type is a 16-bit signed two's complement integer. It has a
minimum value of 32,768 and a maximum value of 32,767 (inclusive). As with byte, the
same guidelines apply: you can use a short to save memory in large arrays, in situations
where the memory savings actually matters.
Int The int data type is a 32-bit signed two's complement integer. It has a minimum
value of 2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral
values, this data type is generally the default choice unless there is a reason (like the above)
to choose something else. This data type will most likely be large enough for the numbers
your program will use, but if you need a wider range of values, use long instead.
Long The long data type is a 64-bit signed two's complement integer. It has a
minimum value of 9,223,372,036,854,775,808 and a maximum value of
9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values
wider than those provided by int.
float The float data type is a single-precision 32-bit IEEE 754 floating point. Its range
of values is beyond the scope of this discussion. As with the recommendations for byte and
short, use a float (instead of double) if you need to save memory in large arrays of floating
point numbers. This data type should never be used for precise values, such as currency.
For that, you will need to use the java.math.BigDecimal.
double The double data type is a double-precision 64-bit IEEE 754 floating point. Its
range of values is beyond the scope of this discussion. For decimal values, this data type is
generally the default choice. As mentioned above, this data type should never be used for
precise values, such as currency.
Boolean The boolean data type has only two possible values: true and false. Use this
data type for simple flags that track true/false conditions. This data type represents one bit
of information, but its "size" isn't something that's precisely defined.
Char The char data type is a single 16-bit Unicode character. It has a minimum value
of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
In addition to the eight primitive data types listed above, the Java programming language
also provides special support for character string via the java.lang.String class.
Enclosing your character string within double quotes will automatically create a new
String object;
for example, String s = "this is a string";
String objects are immutable, which means that once created, their values cannot be
changed. The String class is not technically a primitive data type, but considering the
special support given to it by the language.
Operators
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.
The operators cited below are listed according to precedence order. The closer to the top of
the table an operator appears, the higher its precedence. Operators with higher precedence
are evaluated before operators with relatively lower precedence. Operators on the same line
have equal precedence. When operators of equal precedence appear in the same expression,
a rule must govern which is evaluated first. All binary operators except for the assignment
operators are evaluated from left to right; assignment operators are evaluated right to left.
Operator Precedence
Operators Precedence
postfix expr++ expr--
multiplicative * / %
additive + -
equality == !=
Operator Precedence
Operators Precedence
logical AND &&
logical OR ||
ternary ? :
One of the most common operators that you'll encounter is the simple assignment operator
"=". It assigns the value on its right to the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
The Java programming language provides operators that perform addition, subtraction,
multiplication, and division. There's a good chance you'll recognize them by their
counterparts in basic mathematics. The only symbol that might look new to you is "%",
which divides one operand by another and returns the remainder as its result.
The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value
of a boolean.
The equality and relational operators determine if one operator is greater than, less than,
equal to, or not equal to another operand. The majority of these operators will probably
look familiar to you as well.
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
Example :
class ComparisonDemo {
The && and || operators perform Conditional-AND and Conditional-OR operations on two
boolean expressions. These operators exhibit "short-circuiting" behavior, which means that
the second operand is evaluated only if needed.
&& Conditional-AND
|| Conditional-OR
class ConditionalDemo1 {
Example :
Expressions
int a = 5, b = 2;
double c = 3.0;
Use Chapter 3's operator precedence table to evaluate the following expressions:
(c + a / b) / 10 * 5
(0 % a) + c + (0 / a)
Statements
• Assignment expressions
• Any use of ++ or --
• Method invocations
• Object creation expressions
Such statements are called expression statements. Here are some examples of expression
statements.
aValue = 8933.234; // assignment statement
aValue++; // increment statement
System.out.println("Hello World!"); // method invocation
// statement
Bicycle myBike = new Bicycle(); // object creation
// statement
In addition to expression statements, there are two other kinds of statements: declaration
statements and control flow statements. A declaration statement declares a variable. You've
seen many examples of declaration statements already:
Finally, control flow statements regulate the order in which statements get executed. If, if –
else and switch statements.
Blocks
A block is a group of zero or more statements between balanced braces and can be used
anywhere a single statement is allowed. The following example, illustrates the use of
blocks:
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition)
{ // begin block 1
System.out.println("Condition is true.");
} // end block one
else
{ // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
The statements inside your source files are generally executed from top to bottom, in the
order that they appear. Control flow statements, however, break up the flow of execution
by employing decision making, looping, and branching, enabling your program to
conditionally execute particular blocks of code.
If (condition)
Statement(s);
In addition, the opening and closing braces are optional, provided that the "then" clause
contains only one statement:
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the
code more brittle. If a second statement is later added to the "then" clause, a common
mistake would be forgetting to add the newly required braces. The compiler cannot catch
this sort of error; you'll just get the wrong results.
Example :
import java . io . * ;
}
}
import java . io . * ;
}
}
The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false. The execution is purely based on the condition i.e. if the condition is
true then the statements after if will be executed and else clause will be skipped out and if
the condition is false the statements after if will be skipped where as else block will be
executed.
If (condition)
Statement(s);
else
Statement(s);
Example :
import java . io . * ;
{
public static void main(String[] args)
{
int value1 = 1;
if(value1 > 0)
{ System.out.println("value1 is a positive number"); }
else
{ System.out.println("value1 is a Negative number"); }
if(value1 == 0)
{ System.out.println("value1 is equal to Zero"); }
}
}
import java . io . * ;
}
}
class IfElseDemo {
public static void main(String[] args) {
You may have noticed that the value of testscore can satisfy more than one expression in
the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied,
the appropriate statements are executed (grade = 'C';) and the remaining conditions are
not evaluated.
Unlike if-then and if-then-else, the switch statement allows for any number of
possible execution paths. A switch works with the byte, short, char, and int primitive
data types. Switch is used for when ever you have multiple selections
Switch(expression)
default : statement(s);
Example :
class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}
The body of a switch statement is known as a switch block. Any statement immediately
contained by the switch block may be labeled with one or more case or default labels.
The switch statement evaluates its expression and executes the appropriate case.
1. while loop
2. do while loop
3. for loop
while (expression)
{
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while
block. The while statement continues testing the expression and executing its block until
the expression evaluates to false. Using the while statement to print the values from 1
through 10 can be accomplished as in the following WhileDemo program:
Import java . io . * ;
{
class WhileDemo {
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true)
{
// your code goes here
}
The Java programming language also provides a do-while statement, which can be
expressed as follows:
do
{
statement(s)
}
while (expression);
The difference between do-while and while is that do-while evaluates its expression at
the bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once, as shown in the following DoWhileDemo program:
import java . io . * ;
{
class DoWhileDemo
{
public static void main(String[] args){
int count = 1;
do
{
System.out.println("Count is: " + count);
count++;
}
while (count <= 11);
}
}
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers
often refer to it as the "for loop" because of the way in which it repeatedly loops until a
particular condition is satisfied. The general form of the for statement can be expressed as
follows:
When using this version of the for statement, keep in mind that:
• The initialization expression initializes the loop; it's executed once, as the loop
begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:
import java . io . * ;
{
class ForDemo
{
public static void main(String[] args){
for(int i=1; i<11; i++)
{
System.out.println("Count is: " + i);
}
}
}
The if-then statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates to true.
The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false.
Unlike if-then and if-then-else, the switch statement allows for any number of
possible execution paths.
The while and do-while statements continually execute a block of statements while a
particular condition is true.
The difference between do-while and while is that do-while evaluates its expression at
the bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once.
The for statement provides a compact way to iterate over a range of values. It has two
forms, one of which was designed for looping through collections and arrays.
Function / Method:
A function is infect a sub program that can acts on data and return a value. Each and every
java program must be having at least one function that is “main “. main is the entry point
of a java program operating system starts reading a program from main function.
Up until now, the term function has been used to describe a named subroutine. The term
that is more commonly used in Java is method, as in “a way to do something. It’s really
only a syntactic difference, now a days the term “method” is used rather than “function.”
Calling Function:
C:\jdk1.3\bin>java methods
HI THIS IS MY MAIN PROGRAM
HI THIS IS MY METHOD
Passing values to a function:
HI THIS IS MY MAIN PROGRAM
We can simply pass a value from our main program or form one function to another
function this is call argument. General syntax of passing value form our main function to a
user defined function.
e.g.
table ( 5 );
import java.io.*;
public class method
{
public static void main(String [] arg)
{
table(5);
} C:\jdk1.3\bin>javac
methods.java
public static void table(int a)
{ C:\jdk1.3\bin>java
for(int b=1; b<=10; b++) method
System.out.println(a+" * "+b+"
5 * 1 ==5" + a*b);
} 5 * 2 = 10
} 5 * 3 = 15
5 * 4 = 20
5 * 5 Output
= 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Returning values through a function:
A function can return any type of values to another function or a main function
General syntax of returning values.
Keyboard Input
The most common user interface devices are the CRT display for output and the keyboard
for input. Just as System.out was used to output data on the host system's CRT display,
System.in is used to receive input from the keyboard. To do this, however, the following
initialization is required:
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
This statement sets-up System.in as a buffered character input stream. 1 It's a bit messy, but
there are two important services provided. The InputStreamReader class converts raw bytes
arriving from the keyboard into characters. Second, and the BufferedReader class buffers
(temporary stores) the characters to provide efficient reading from the input stream.. The
statement declares and instantiates an object named stdin of the BufferedReader class. This
is analogous to earlier statements that declared and initialized variables. Now, however,
instead of a primitive data type, we have a class (BufferedReader) and instead of a variable,
we have an object (stdin). So an object is "kind of like" a variable, and a class is "kind of
like" a data type. Following the above statement, a line of text is read from the keyboard as
follows:
String line = stdin.readLine();
Think of stdin.readLine() as an expression, which it is. As an expression, it is evaluated and
it yields a value. This value is assigned to the variable line. More precisely, the readLine()
method is called on the stdin object — the keyboard. A string is returned and assigned to
the String variable line. The string contains the characters of a line of text entered on the
keyboard.
A line of input ends when the user presses the Enter key. The Enter key generates an end-
of-line code, but this is not included in the string returned by the readLine() method.
import java.io.*;
System.out.println(line);
public by
Through class input
above statement the input string is printed.
{
If we want thestatic
public user void
to enter a numberargs)
main(String[] on the keyboard,
throws then we must once again
IOException
{
confront(tackle, face) the problem of converting one type to another. For example, if the
user types 3, followed by 5, followed
BufferedReader stdin = by the Enter key, then the String variable line
new BufferedReader(new
contains the character '3' and the characterInputStreamReader(System.in));
'5', as opposed to the integer 35. So before the
value entered can be operated on as an integer,
System.out.print("Please enterthe string
your must");
name: be converting to an int.
String name = stdin.readLine();
}
Converting String data to integer or double
The main() method is defined with the throws IOException clause. This is required because
certain types of errors, known as exceptions, are possible with keyboard input. A throws
clauseimport java.io.*;
informs the compiler that we are aware of the possibility of such errors and that we
will deal withclass
public theminput
in an appropriate manner.
{
public static void main(String[] args) throws IOException
Converting {
String to integer or float
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
Objects:
An object is used to represent real world entities, such as person, place, thing,
concept etc. that has either physical or conceptual existence that we find in
normal day life. E.g. person, car, book, loan etc.
Tangible Things as a car, printer, ...
Roles as employee, boss, ...
Incidents as flight, overflow, ...
Interactions as contract, sale, ...
Specifications as colour, shape, …
Every object has certain properties (or attributes or characteristics or features)
on the basis of which we can distinguish one object from another.
For example the person object has certain properties like name, age, date of
birth, gender etc. Also every object performs certain operations. For example
the person object can perform operations like move, listen, speak, sit etc.
Name
gender
speak
listen
n
age
Date of birth
Sit Move
The objects that are used in programming are also designed in the similar manner. They
have certain properties called data member and they perform various operations called
member functions
Identi Beha
State
fier vior
State: - (Properties, attributes, characteristics of an object)
Behavior:- Any method / function or action which can be performed by an
object is called behavior.
Class:
Class is a user defined data structure which contains both the attributes and
behavior and unique name.
Unique:- Every class must be have a unique name because OOPs
provides the concept of inheritance, so we can create more than one
classes with distinct name.
Behavior: - Any method/ Function which performed some specific
action are known as behavior.
State: - Attributes/ Characteristics of the class.
General Structure of a Class
Attribute Attribute
-1 -2
Function Function
-1 -2
Function
-3
Class
Header Files
Class className
{
Private :
Attribute1, 2, 3…..
Public:
member function1
member function2
…………………...
}
Public MainClass
{
Main Function
{
instantiation
}
}
Object Vs Classes:
We can create many objects of a single class but inverse is not
allowed.
Objects encapsulate the state and behavior of the class but inverse is
not possible.
Once a class is defined, it will occupy some of the disc space. But
objects can be created and destroyed for many time.
Object reserves memory space.
Class Example
The very first class “ first” program having one member function mymain the object
for the first class is created by the name of myobj.
class first
{
public void myfunc( )
{
System.out.println(“ hi this is my first class “) ;
}
}
A class add B
{
class add private int a, b, c , d, e;
{ public void getdata( )
private int a, b, c; {
a = 64 ;
public void getdata( ) b = 45 ;
{ }
a = 64 ;
b = 45; public void sum ( )
} {
c = a+b;
public void showdata( ) System.out.println( “ 64 + 45 is “ + c);
{ }
c = a+b;
System.out.println( “ 64 + 45 is “ + c); public void sub ( )
} {
} d = a+b;
System.out.println( “ 64 - 45 is “ + d);
public class sum }
{
public static void main ( String [ ] arg) public void mul ( )
{ {
add myobject = new add ( ); e = a*b;
myobject . getdate ( 15 , 45 ) ; System.out.println( “ 64 * 45 is “ + e);
}
myobject . getdate ( ) ;
}
}
} public class sum
{
public static void main ( String [ ] arg)
{
add myobject = new add ( );
myobject . getdata ( ) ;
myobject . sum ( ) ;
myobject . sub ( ) ;
myobject . mul ( ) ;
}
}
Sending values from main class to a user defined Class
(Member Function)
public void getdata( int x , int y ) public void getdata( int i , int j)
{ {
a = x; a = i;
b = y; b = j;
} }
}
}
Using classes write a program to send a number to a “ Table “class
and over there display the table of that number
import java . io . * ;
class Table
{
private int no , a;
}
}
Returning values for Sub class to main class
public int myfunc( int x , int y ) public void sum ( int x , int y)
{ {
c = x+y; plus = x + y ;
return c ; return plus ;
} }
}
}
Constructors :
class test
{
public test ( )
{
//body of constructor ;
}
}
}
import java . io . * ;
class Table
{
private int no , a;
}
}
POLYMORPHISM
POLYMORPHISM
class test
{
member variables ;
}
import java . io . * ; import java . io . * ;
class add class Table
{ {
private int a , b , c; private int a , no;
} }
} }
INHERITANCE
Inheritance is one of the important pillars of object oriented
programming. Inheritance is the process of creating new classes from the
exiting class without modifying the existing one. Generally inheritance
means taking the behavior and characteristics of the original (bass class) in
an extended new class (derived class). Inheritance supports a number of
design goals in java i.e. inheritance enables us to reuse code that we know
works (code reuse). The process of inheritance is also known as ‘derivation’.
Simply inheritance is the method of creating new classes from existing/old
one. The new class is called derived class/ subclass/ child class or
descendent class and the exiting/old class is called base class/ super
class/ parent class or ancestor class.
The derived class can inherit some or all features (data and functions) of the
base class and can add its own features to extend the functionality of the
base class. But in this whole procedure the base class does not get
affected.
Class-
B
Feature-1
Feature-2 Subclass or child class or descendent
Feature-3 class
Daily life Example (1/2)
Now if we have to add any new feature, like address, that is common to all
three classes, which will be putted into employee class instead of adding
separately to worker, manager and clerk classes. Only distinct features are
required to be added separately to these classes.
INHERITANCE BASICS
To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword. To see how. Let’s begin with a short
example, the following program creates a super class A and a sub class
called B. Notice how the keyword extends is used to create a sub class of A
class A
{
int i , j ;
class B extends A
{
int k ;
obj . showij ( ) ;
obj . showk ( ) ;
obj . sum ( ) ;
}
}
import java.io.*;
class father
{
String name;
int age;
obj.getdata("Raheem",56);
obj.fatherdata( );
obj.getdata("Sultan",23);
obj.sondata( );
}
Super and this key words
The super key word is use for two specific purposes. The first calls the super
class constructor. The second is use to access a member of the super class
that has been hidden by a member of a sub class.
Using super to access super class member variables:-
Through super keyword inside into a sub class we can call super class
member variables e.g.
super . member_variable ;
Using super to call super class constructors:-
A sub class can call a constructor method defined by its superclass by use
of the following form of super.
super( parameter_list ) ;
This
some time a method will need to refer to the object that invoked it. To allow
this java defines this keyword. this can be used inside any method to refer to
the current object. That is “this” keyword is always a reference to the object
on which the method was invoked.
e.g. this. member_variable ;
import java.io.*;
class A
{
int i;
}
class B extends A
{
int i;
{
B obj=new B(5,10);
obj.show();
}
}
import java.io.*;
class A
{
int i,j;
class B extends A
{
int k;
{
B obj=new B(5,10,15);
obj.show();
}
}