Java Class
Java Class
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides
many concepts such as inheritance, data binding, polymorphism, etc.
Simula is considered the first object-oriented programming language. The programming paradigm where
everything is represented as an object is known as a truly object-oriented programming language.
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to implement real-world entities for example object, classes,
abstraction, inheritance, polymorphism, etc.
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviours of a
parent object. It is an important part of OOPs (Object Oriented programming system).
1
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class private.
Now we can use setter and getter methods to set and get the data in it. The Java Bean class is the
example of a fully encapsulated class.
2
Let's see some real life example of class and object in java to understand the difference well:
Class: Human
Class: Fruit
Class: Food
A class is a template for multiple objects with similar features. Classes embody all the features of a particular set
of objects.When you write a program in an object-oriented language, you don’t define actual objects. You define
classes of objects.
An instance of a class is another word for an actual object. If classes are an abstract representation of an object,
an instance is its concrete representation. So what, precisely, is the difference between an instance and an object?
Nothing, really. Object is the more general term, but both instances and objects are the concrete representation
of a class. In fact, the terms instance and object are often used interchangeably in OOP language. An instance of a
tree and a tree object are both the same thing.
Attributes of an object can also include information about its state; for example, you could have features for
engine condition (off or on) or current gear selected. Attributes are defined by variables; in fact, you can
consider them analogous to global variables for the entire object. Because each instance of a class can have
different values for its variables, each variable is called an instance variable.
Instance variables define the attributes of an object. The class defines the kind of attribute, and each instance
stores its own value for that attribute. Each attribute, as the term is used here, has a single corresponding
instance variable; changing the value of a variable changes the attribute of that object. Instance variables may be
set when an object is created and stay constant throughout the life of the object, or they may be able to change
at will as the program runs. In addition to instance variables, there are also class variables, which apply to the
class itself and to all its instances. Unlike instance variables, whose values are stored in the instance, class
variables’ values are stored in the class itself.
Behavior
A class’s behavior determines what instances of that class do when their internal state changes or when that
instance is asked to do something by another class or object. Behavior is the way objects can do anything to
themselves or have anything done to them. For example, to go back to the theoretical Motorcycle class, here are
some behaviors that the Motorcycle class might have:
Start the engine
Stop the engine
Speed up
Change gear
Stall
To define an object’s behavior, you create methods, which look and behave just like functions in other
languages, but are defined inside a class. Java does not have functions defined outside classes (as C++ does).
4
Methods are functions defined inside classes that operate on instances of those classes.
Methods don’t always affect only a single object; objects communicate with each other using methods as well. A
class or object can call methods in another class or object to communicate changes in the environment or to ask
that object to change its state. Just as there are instance and class variables, there are also instance and class
methods. Instance methods (which are so common they’re usually just called methods) apply and operate on an
instance; class methods apply and operate on a class (or on other objects).
Creating a Class
Up to this point, today’s lesson has been pretty theoretical. In this section, you’ll create a working example of the
Motorcycle class so that you can see how instance variables and methods are defined in a class. You’ll also
create a Java application that creates a new instance of the Motorcycle class and shows its instance variables.
Inheritance
Inheritance is one of the most crucial concepts in object-oriented programming, and it has a very direct effect on
how you design and write your Java classes. Inheritance is a powerful mechanism that means when you write a
class you only have to specify how that class is different from some other class, while also giving you dynamic
access to the information contained in those other classes. With inheritance, all classes—those you write, those
from other class libraries that you use, and those from the standard utility classes as well—are arranged in a
strict hierarchy .
Each class has a superclass (the class above it in the hierarchy), and each class can have one or more subclasses
(classes below that class in the hierarchy). Classes further down in the hierarchy are said to inherit from classes
further up in the hierarchy.
Variables
Recall that Java classes have only a single superclass, and they inherit variables and methods from that
superclass and all its superclasses. Although single inheritance makes the relationship between classes and the
5
functionality those classes implement easy to understand and to design, it can also be somewhat restricting—in
particular, when you have similar behavior that needs to be duplicated across different “branches” of the class
hierarchy. Java solves this problem of shared behavior by using the concept of interfaces.
An interface is a collection of method names, without actual definitions, that indicate that a class has a set of
behaviors in addition to the behaviors the class gets from its super classes.
Although a single Java class can have only one super class (due to single inheritance) that class can also
implement any number of interfaces. By implementing an interface, a class provides method implementations
(definitions) for the method names defined by the interface. If two very disparate classes implement the same
interface, they can both respond to the same method calls (as defined by that interface), although what each
class actually does in response to those method calls may be very different.
Packages in Java are a way of grouping together related classes and interfaces. Packages enable modular groups
of classes to be available only if they are needed and eliminate potential conflicts between class names in
different groups of classes.
Class: A template for an object, which contains variables and methods representing behavior and attributes.
Classes can inherit variables and methods from other classes.
Object: A concrete instance of some class. Multiple objects that are instances of the same class have access to the
same methods, but often have different values for their instance variables.
Instance: The same thing as an object; each object is an instance of some class.
Super class: A class further up in the inheritance hierarchy than its child, the subclass.
Subclass: A class lower in the inheritance hierarchy than its parent, the superclass. When you create a new
class, that’s often called sub classing.
Instance method: A method defined in a class, which operates on an instance of that class. Instance methods are
usually called just methods.
Class method: A method defined in a class, which can operate on the class itself or on any object.
Instance variable: A variable that is owned by an individual instance and whose value is stored in the instance.
6
Class variable: A variable that is owned by the class and all its instances as a whole, and is stored in the class.
Interface: A collection of abstract behavior specifications that individual classes can then implement.
Package: A collection of classes and interfaces. Classes from packages other than java.lang must be explicitly
imported or referred to by full package name.
History of Java
Java was originally designed for interactive television, but it was too advanced technology for the digital cable
television industry at the time. The history of java starts with Green Team. Java team members (also known
as Green Team), initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was suited for internet programming. Later, Java technology was incorporated by
Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured,
High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted and Dynamic".
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. There are
given the significant points that describe the history of Java.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The
small team of sun engineers called Green Team. Firstly, it was called "Greentalk" by James Gosling, and file
extension was .gt. After that, it was called Oak and was developed as a part of the Green project. In 1995, Oak
was renamed as "Java" because it was already a trademark by Oak Technologies.
Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in
the popularity of this language. The features of Java are also known as java buzzwords.
7
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Compile and Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
In this page, we will learn how to write the simple program of java. We can write a simple hello java program
easily after installing the JDK.
To create a simple java program, you need to create a class that contains the main method. Let's understand the
requirement first.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the java program
8
o Compile and run the java program
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Test it Now
Output:Hello Java
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code into byte code.
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
9
Objects and Classes
When you write a computer program, you put it together from certain “building blocks”. In Java, you build
programs from objects. Each object has a particular behavior, and you can manipulate it to achieve certain
effects.
Classes
You encountered two objects:
• System.out
• “Hello, World!”
Each of these objects belongs to a different class. The System.out object belongs to the PrintStream class. The
“Hello, World!” object belongs to the String class. Of course, there are many more String objects, such as
“Goodbye” or “Mississippi”. They all have something in common––you can invoke the same methods on all
strings.
Using Objects
An object is an entity that you can manipulate by calling one or more of its methods.
A method consists of a sequence of instructions that can access the internal data of an object. When you call the
method, you do not know exactly what those instructions are, or even how the object is organized internally.
However, the behavior of the method is well defined, and that is what matters to us when we use it.
Statements sometimes return values—for example, when you add two numbers together or test to see whether
one value is equal to another. These kind of statements are called expressions. The most important thing to
remember about Java statements is that each one ends with a semicolon. Forget the semicolon and your Java
program won’t compile. Java also has compound statements, or blocks, which can be placed wherever a single
statement can. Block statements are surrounded by braces ({ }).
A variable is a container which holds the value while the java program is executed. A variable is
assigned with a datatype.
Variable is a name of memory location. There are three types of variables in java: local, instance and
static.
There are two types of data types in java: primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
11
1. int data=50;//Here data is variable
1. int data=50;//Here data is variable
Types of Variables
There are three types of variables in java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
12
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory.
Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java statement can go),
although they are most commonly declared at the beginning of the definition before they are used:
You can string together variable names with the same type:
int x, y, z;
String firstName, LastName;
13
You can also give each variable an initial value when you declare it:
int myAge, mySize, numShoes = 28;
String myName = “Laura”;
boolean isTired = true;
int a = 4, b = 5, c = 6;
If there are multiple variables on the same line with only one initializer (as in the first of the previous
examples), the initial value applies to only the last variable in a declaration. You can also group individual
variables and initializers on the same line using commas, as with the last example, above.
Local variables must be given values before they can be used (your Java program will not compile if you try to
use an unassigned local variable). For this reason, it’s a good idea always to give local variables initial values.
Instance and class variable definitions do not have this restriction (their initial value depends on the type of the
variable: null for instances of classes, 0 for numeric
variables, ‘\0’ for characters, and false for booleans).
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color,
Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable,
Remote, ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(),
main(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
14
Declaring a Class
Line 4
begins a class declaration for class Welcome1. Every Java program consists of at least one class that you (the
programmer) define. The class keyword introduces a class declaration and is immediately followed by the
class name (Welcome1). Keywords (sometimes called reserved words) are reserved for use by Java and are
always spelled with all lowercase letters.
The complete list of keywords.
Class Names and Identifiers
By convention, class names begin with a capital letter and capitalize the first letter of each word they include
(e.g., SampleClassName). A class name is an identifier—a series of characters consisting of letters, digits,
underscores (_) and dollar signs ($) that does not begin with a digit and does not contain spaces. Some valid
identifiers are Welcome1, $value, _value, m_inputField1 and button7. The name 7button is not a valid identifier
because it begins with a digit, and the name input field is not a valid identifier because it contains a space.
Normally, an identifier that does not begin with a capital letter is not a class name. Java is case sensitive—
uppercase and lowercase letters are distinct—so value and Value are different (but both valid) identifiers.
every class we define begins with the public keyword. For now, we simply require this keyword.
For our application, the file name is Welcome1.java.
We also have public and non-public classes.
A public class must be placed in a file that has the same name as the class (in terms of both spelling and
capitalization) plus the .java extension; otherwise, a compilation error occurs.
For example, public class Welcome must be placed in a file named Welcome.java.
A left brace {, begins the body of every class declaration. A corresponding right brace }, must end each class
declaration. Lines are indented in Java.
Program 2
Escape Sequence
16
Program 4:Displaying Text with printf
Operators in Java
additive +-
equality == !=
bitwise ^
exclusive OR
bitwise inclusive |
OR
Logical logical AND &&
logical OR ||
17
Ternary ternary ?:
Output:
10
12
12
10
Output:
22
21
Output:
-11
9
false
true
19
Java Arithmetic Operators
Java arithmatic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.
Output:
15
5
50
2
0
Output:
20
21
Output:
40
80
80
240
21
6. }}
Output:
2
5
2
Output:
5
5
-5
1073741819
The bitwise & operator always checks both conditions whether first condition is true or false.
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
22
7. System.out.println(a<b&a<c);//false & true = false
8. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}
Output:
false
false
Output:
false
10
false
11
23
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}
Output:
true
true
true
10
true
11
24
Java Ternary Operator Example
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
Another Example:
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
25
Java Assignment Operator Example
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
Output:
14
16
26
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}
Output:
13
9
18
9
Output:
1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}
1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
27
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}
Output:
20
Another Application: Adding Integers
Our next application reads (or inputs) two integers (whole numbers, such as –22, 7, 0 and 1024) typed by a
user at the keyboard, computes their sum and displays it. This program must keep track of the numbers
supplied by the user for the calculation later in the program.
Programs remember numbers and other data in the computer’s memory and access that data through program
elements called variables.
Import Declarations
28
These classes are grouped into Packages name groups of related classes and are collectively referred to as the
Java Class library or Java Application Programming Interface (Java API).
The above is am import declaration that helps the compiler locate a class that is used in this program.It
indicates that this example uses Java predefined Scanner class from java.util package.
Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in java.
o for loop
o while loop
o do-while loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is
recommended to use for loop.
29
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
Syntax:
1. for(initialization;condition;incr/decr)
2. {
3. //statement or code to be executed
4. }
Flowchart:
Example:
If we have to perform only one operation, having same name of the methods increases the readability
of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior of
the method because its name differs.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
31
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
1. class TestOverloading4{
2. public static void main(String[] args){System.out.println("main with String[]");}
3. public static void main(String args){System.out.println("main with String");}
4. public static void main(){System.out.println("main without args");}
5. }
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
33
Understanding Type
Let's understand the type of instance.
1. int data=30;
1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.
If there is any private, final or static method in a class, there is static binding.
1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
34
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
35