Oop CH 5-8
Oop CH 5-8
4th
Class abstraction
As per dictionary, abstraction is the quality of dealing with ideas rather than events. For
example, when you consider the case of e-mail, complex details such as what happens as
soon as you send an e-mail, the protocol your e-mail server uses are hidden from the user.
Therefore, to send an e-mail you just need to type the content, mention the address of the
receiver, and click send.
Java Abstraction
Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user. In other words, the user will have the
information on what the object does instead of how it does it. In Java programming,
abstraction is achieved using Abstract classes and interfaces.
Java Abstract Classes
A java class which contains the abstract keyword in its declaration is known as abstract
class.
Java abstract classes may or may not contain abstract methods, i.e., methods without body
( public void get(); )
But, if a class has at least one abstract method, then the class must be declared abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.
Example :
SREZ
Page 1
Object Oriented Programming -I B.E.4th
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}
If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the parent
class as an abstract.
abstract keyword is used to declare the method as abstract.
You have to place the abstract keyword before the method name in the method
declaration.
An abstract method contains a method signature, but no method body.
Instead of curly braces, an abstract method will have a semi colon (;) at the end.
SREZ
Page 2
Object Oriented Programming -I B.E.4th
Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three
are inheritance, polymorphism , and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class will
be hidden from other classes, and can be accessed only through the methods of their
current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
Example :
SREZ
Page 3
Object Oriented Programming -I B.E.4th
}
public String getName()
{
return name;
}
public String getIdNum(
{
return idNum;
}
public void setAge( int newAge
{
age = newAge;
}
The public setXXX() and getXXX() methods are the access points of the instance
variables of the EncapTest class. Normally, these methods are referred as getters and
setters. Therefore, any class that wants to access the variables should access them through
these getters and setters.
The variables of the EncapTest class can be accessed using the following program −
SREZ
Page 4
Object Oriented Programming -I B.E.4th
Output:
Name : James Age : 20
Benefits of Encapsulation -
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
class Person {
private String name = "Robert";
private int age = 21;
SREZ
Page 5
Object Oriented Programming -I B.E.4th
// Getter methods
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
public class Main {
public static void main(String args[]) {
// Object to Person class
Person per = new Person();
// Getting and printing the values
System.out.println("Name of the person is: " + per.getName());
System.out.println("Age of the person is: " + per.getAge());
}
Output
Name of the person is: Robert
Age of the person is: 21
// Class "Person"
class Person {
private String name;
private int age;
// Setter Methods
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
public class Main {
public static void main(String args[]) {
// Object to Person class
Person per = new Person();
// Setting the values
SREZ
Page 6
Object Oriented Programming -I B.E.4th
per.setName("Robert");
per.setAge(21);
1. Identify real-world entities: Start by identifying the real-world entities or concepts that
your program needs to model. These could be tangible objects like cars, employees, or
buildings, or abstract concepts like transactions, accounts, or messages.
2. Define classes: Once you've identified the entities, create classes to represent them. A class
is a blueprint for creating objects, defining their properties (attributes) and behaviors
(methods).
3. Encapsulation: Encapsulate related data and behavior within classes. This means that the
internal workings of an object should be hidden from the outside world, and only a well-
defined interface (public methods) should be exposed for interacting with the object.
4. Inheritance: Use inheritance to create a hierarchy of classes where more specialized classes
(subclasses) inherit attributes and behaviors from more general classes (superclasses). This
promotes code reuse and allows for modeling of "is-a" relationships.
6. Association: Model relationships between classes using association, where objects of one
class are connected to objects of another class. Associations can be one-to-one, one-to-many,
or many-to-many.
By thinking in terms of objects and class relationships, you can design more modular,
reusable, and maintainable software systems that closely model real-world entities and their
interactions. This approach facilitates better organization, understanding, and scalability of
your codebase.
Java Inheritance
Inheritance is a process where one class acquires the properties (methods and attributes)
of another. With the use of inheritance, the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).
To implement (use) inheritance in Java, the extends keyword is used. It inherits the properties
(attributes or/and methods) of the base class to the derived class. The word "extends" means
to extend functionalities i.e., the extensibility of the features.
Syntax to implement inheritance
class Super {
.....
.....
.....
.....
SREZ
Page 8
Object Oriented Programming -I B.E.4th
Example
Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
In the given program, when an object to My_Calculation class is created, a copy of the
contents of the superclass is made within it. That is why, using the object of the subclass
you can access the members of a superclass.
The Superclass reference variable can hold the subclass object, but using that variable you
can access only the members of the superclass, so to access the members of both classes it
is recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below. But using
the superclass reference variable ( cal in this case) you cannot call the
method multiplication(), which belongs to the subclass My_Calculation.
SREZ
Page 9
Object Oriented Programming -I B.E.4th
The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.
It is used to differentiate the members of superclass from the members of subclass, if they
have same names.
It is used to invoke the superclass constructor from subclass.
If a class is inheriting the properties of another class. And if the members of the superclass
have the names same as the sub class, to differentiate these variables we use super keyword
as shown below.
super.variable
super.method();
If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the superclass. But if you want to call a parameterized constructor of
the superclass, you need to use the super keyword as shown below.
super(values);
Example :
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String args[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}
instanceof keyword is used to check whether an object belongs to a particular class or its
subclass. It's a binary operator that returns true if the object is an instance of the specified
class, or false otherwise.
class Animal {}
SREZ
Page 10
Object Oriented Programming -I B.E.4th
In this example, we have two classes: Animal and Dog, where Dog is a subclass of Animal.
We create instances of both classes (animal and dog), and then we use the instanceof operator
to check their types.
In Java, there are mainly three types of inheritances Single, Multilevel, and Hierarchical.
Java does not support Multiple and Hybrid inheritance.
SREZ
Page 11
Object Oriented Programming -I B.E.4th
A very important fact to remember is that Java does not support multiple and hybrid
inheritances. This means that a class cannot extend more than one class. Therefore following
is illegal −
The inheritance in which there is only one base class and one derived class is known as single
inheritance. The single (or, single-level) inheritance inherits data from only one base class to
only one derived class.
Example
class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}
// Calling method
obj.printOne();
}
}
Output
printOne() method of One class.
The inheritance in which a base class is inherited to a derived class and that derived class is
further inherited to another derived class is known as multi-level inheritance. Multilevel
inheritance involves multiple base classes.
Example
class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}
class Two extends One {
public void printTwo() {
System.out.println("printTwo() method of Two class.");
SREZ
Page 12
Object Oriented Programming -I B.E.4th
// Calling methods
obj.printOne();
obj.printTwo();
}
}
Output
printOne() method of One class.
printTwo() method of Two class.
The inheritance in which only one base class and multiple derived classes is known as
hierarchical inheritance.
Example
// Base class
class One {
public void printOne() {
System.out.println("printOne() Method of Class One");
}
}
// Derived class 1
class Two extends One {
public void printTwo() {
System.out.println("Two() Method of Class Two");
}
}
// Derived class 2
class Three extends One {
public void printThree() {
System.out.println("printThree() Method of Class Three");
}
}
SREZ
Page 13
Object Oriented Programming -I B.E.4th
// Testing CLass
public class Main {
public static void main(String args[]) {
Two obj1 = new Two();
Three obj2 = new Three();
Output
printOne() Method of Class One
printOne() Method of Class One
Aggregation :
An aggregation is a relationship between two classes where one class contains an instance of
another class. For example, when an object A contains a reference to another object B or we
can say Object A has a HAS-A relationship with Object B, then it is termed as Aggregation in
Java Programming.
Aggregation in Java helps in reusing the code. Object B can have utility methods and which
can be utilized by multiple objects. Whichever class has object B then it can utilize its
methods.
Example
In this example, we're creating few classes like Vehicle, Speed. A Van class is defined which
extends Vehicle class and has a Speed class object. Van class inherits properties from Vehicle
class and Speed being its property, we're passing it from caller object. In output, we're
printing the details of Van object.
package com.tutorialspoint;
class Vehicle{
private String vin;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
SREZ
Page 14
Object Oriented Programming -I B.E.4th
}
class Speed{
private double max;
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
}
class Van extends Vehicle {
private Speed speed;
public Speed getSpeed() {
return speed;
}
public void setSpeed(Speed speed) {
this.speed = speed;
}
public void print() {
System.out.println("Vin: " +this.getVin() + ", Max Speed: " + speed.getMax() );
}
}
public class Tester {
public static void main(String[] args) {
Speed speed = new Speed();
speed.setMax(120);
Van van = new Van();
van.setVin("abcd1233");
van.setSpeed(speed);
van.print();
}
}
Output
Vin: abcd1233, Max Speed: 120.0
Polymorphism
Polymorphism is the ability of an object to take on many forms. Polymorphism is an
important feature of Java OOP concepts and it allows us to perform multiple operations by
using the single name of any method (interface). Any Java object that can pass more than one
IS-A test is considered to be polymorphic. In Java, all java objects are polymorphic since any
object will pass the IS-A test for its own type and for the class Object.
The most common use of polymorphism in OOP occurs when a parent class reference is
used to refer to a child class object.
SREZ
Page 15
Object Oriented Programming -I B.E.4th
It is important to know that the only possible way to access an object is through
a reference variable. A reference variable can be of only one type. Once declared, the type
of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared
final. The type of the reference variable would determine the methods that it can invoke
on the object.
A reference variable can refer to any object of its declared type or any subtype of its
declared type. A reference variable can be declared as a class or interface type.
Example :
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above examples −
Polymorphism Implementation
interface Vegetarian{}
class Animal{}
public class Deer extends Animal implements Vegetarian{
public static void main(String[] args) {
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
System.out.println(d instanceof Deer);
System.out.println(a instanceof Deer);
System.out.println(v instanceof Deer);
System.out.println(o instanceof Deer);
}
}
Output
true
true
true
true
SREZ
Page 16
Object Oriented Programming -I B.E.4th
Example:
Run time polymorphism is also known as dynamic method dispatch and it is implemented by
the method overloading
Example:
class Vehicle {
public void displayInfo() {
System.out.println("Some vehicles are there.");
}
}
Output
I have a Car.
I have a Bike.
Aggregation
An aggregation is a relationship between two classes where one class contains an instance of
another class. For example, when an object A contains a reference to another object B or we
can say Object A has a HAS-A relationship with Object B, then it is termed as Aggregation in
Java Programming.
SREZ
Page 18
Object Oriented Programming -I B.E.4th
Aggregation in Java helps in reusing the code. Object B can have utility methods and
which can be utilized by multiple objects. Whichever class has object B then it can
utilize its methods.
Primitive data types are the most basic data types provided by a programming language.
They are predefined by the language and typically represent simple values such as
integers, floating-point numbers, characters, and boolean values.
Examples of primitive data types in Java include:
- `int`: Represents integer numbers.
- `double`: Represents floating-point numbers.
- `char`: Represents a single character.
- `boolean`: Represents true or false values.
Primitive data types are not objects and do not have methods or properties associated with
them.
They are used to store simple values directly in memory.
2. Wrapper Classes:
Wrapper classes in Java are classes that provide a way to use primitive data types as
objects.
Each primitive data type in Java has a corresponding wrapper class that allows you to
perform various operations on the primitive data type as if it were an object.
Wrapper classes are part of the `java.lang` package and are used to convert primitive data
types into objects.
Examples of wrapper classes in Java include:
- `Integer`: Wraps an `int` value.
- `Double`: Wraps a `double` value.
- `Character`: Wraps a `char` value.
- `Boolean`: Wraps a `boolean` value.
Wrapper classes provide methods to perform conversions, comparisons, and other
operations on primitive data types.
They are often used in scenarios where objects are required, such as collections like
`ArrayList` or when working with libraries that expect objects rather than primitives.
Wrapper classes are useful when you need to treat primitive data types as objects, such as
when using collections like `ArrayList` or when passing values to methods that expect
objects. They provide additional functionality and flexibility compared to primitive data
types alone.
`BigInteger` and `BigDecimal` are classes in Java that belong to the `java.math` package and
are used for handling large numbers and arbitrary-precision arithmetic, which means they can
handle numbers with more digits than primitive data types like `int` or `double` can represent.
SREZ
Page 19
Object Oriented Programming -I B.E.4th
1. BigInteger:
```java
import java.math.BigInteger;
2. BigDecimal :
```java
import java.math.BigDecimal;
SREZ
Page 20
Object Oriented Programming -I B.E.4th
Both `BigInteger` and `BigDecimal` provide methods for various mathematical operations
and comparisons, allowing precise manipulation of large integer and decimal values without
losing accuracy due to limitations of primitive data types.
String Class
Strings are a sequence of characters. In Java programming language, strings are treated
as objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object
with its value in this case, "Hello world".
As with any other object, you can create String objects by using the new keyword and
a constructor. The String class has 11 constructors that allow you to provide the initial
value of the string using different sources, such as an array of characters.
Example
public class StringDemo
{
public static void main(String args[])
{
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
Output :
Hello
String Length :
SREZ
Page 21
Object Oriented Programming -I B.E.4th
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the
number of characters contained in the string object.
The following program is an example of length(), method String class.
Example
public class StringDemo
{
public static void main(String args[])
{
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
Output
String Length is : 17
Concatenating Strings
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also
use the concat() method with string literals, as in −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
which results in −
"Hello, world!"
Example
Output
Dot saw i was Tod
You have printf() and format() methods to print output with formatted numbers. The
String class has an equivalent class method, format(), that returns a String object rather
than a PrintStream object.
SREZ
Page 22
Object Oriented Programming -I B.E.4th
Using String's static format() method allows you to create a formatted string that you can
reuse, as opposed to a one-time print statement. For example, instead of −
Example to Create Formatted Strings in Java
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
String Comparison
SREZ
Page 23
Object Oriented Programming -I B.E.4th
System.out.println(str1.compareTo(str2)); // Outputs: -1
System.out.println(str2.compareTo(str1)); // Outputs: 1
It's important to choose the appropriate method based on the specific requirements of your
comparison (e.g., content equality, lexicographical ordering, case-insensitive equality).
In Java, there are methods available in the `String` class to convert the case of strings to
uppercase or lowercase. These methods are useful for manipulating strings and performing
case-insensitive comparisons. Here are the methods:
1. toUpperCase():
This method converts all of the characters in the invoking `String` object to uppercase
using the rules of the default locale.
Syntax:
String upperCaseString = originalString.toUpperCase();
Example:
SREZ
Page 24
Object Oriented Programming -I B.E.4th
2.toLowerCase():
This method converts all of the characters in the invoking `String` object to lowercase
using the rules of the default locale.
Syntax:
String lowerCaseString = originalString.toLowerCase();
Example:
These methods return a new `String` object with the characters converted to uppercase or
lowercase, leaving the original `String` object unchanged, as `String` objects in Java are
immutable.
Searching Strings
In Java, you can perform searching operations on strings using various methods provided by
the `String` class. Here are some commonly used methods for searching strings:
1. indexOf():
This method returns the index of the first occurrence of a specified substring within the
string. If the substring is not found, it returns -1.
Syntax:
int index = str.indexOf(substring);
Example:
2. lastIndexOf():
This method returns the index of the last occurrence of a specified substring within the
string. If the substring is not found, it returns -1.
Syntax:
int lastIndex = str.lastIndexOf(substring);
Example:
3. startsWith():
SREZ
Page 25
Object Oriented Programming -I B.E.4th
This method checks whether the string starts with a specified prefix.
Syntax:
boolean startsWith = str.startsWith(prefix);
Example:
4. endsWith():
This method checks whether the string ends with a specified suffix.
Syntax:
boolean endsWith = str.endsWith(suffix);
- Example:
The StringBuffer and StringBuilder classes are used when there is necessity
to make a lot of modifications to Strings of characters.
Unlike Strings, objects of type StringBuffer and String builder can be modified
over and over again without leaving behind a lot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference
between the StringBuffer and StringBuilder is that StringBuilders methods are
not thread safe (not synchronised).
It is recommended to use StringBuilder whenever possible because it is faster
than StringBuffer. However, if the thread safety is necessary, the best option is
StringBuffer objects.
Example
Output
test String Buffer
StringBuffer Methods
SREZ
Page 26
Object Oriented Programming -I B.E.4th
Methods overloading
When a class has two or more methods by the same name but different parameters, at the
time of calling based on the parameters passed respective method is called (or respective
method body will be bonded with the calling line dynamically). This mechanism is known as
method overloading.
Advantage of Method Overloading
Method overloading improves the code readability and reduces code redundancy.
Method overloading also helps to achieve compile-time polymorphism.
Example
If you observe the following example, Here we have created a class named Tester this
class has two methods with same name (add) and return type, the only difference is
the parameters they accept (one method accepts two integer variables and other
accepts three integer variables).
class Calculator
{
public static int add(int a, int b)
{
return a + b;
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}
SREZ
Page 27
Object Oriented Programming -I B.E.4th
When you invoke the add() method based on the parameters you pass respective method body
gets executed.
Method overloading cannot be achieved using following ways while having same
name methods in a class. Compiler will complain of duplicate method presence.
o Using different return type
o Using static and non-static methods
In this example, we've created a Calculator class having two static methods with same name
but different arguments to add two and three int values respectively. In main() method, we're
calling these methods and printing the result. Based on the type of arguments passed,
compiler decides the method to be called and result is printed accordingly.
package com.tutorialspoint;
class Calculator
{
public static int add(int a, int b)
{
return a + b;
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}
SREZ
Page 28
Object Oriented Programming -I B.E.4th
Output
60
150
Method Overriding
Method overriding allows us to achieve run-time polymorphism and is used for writing
specific definitions of a subclass method that is already defined in the superclass.
The method is superclass and overridden method in the subclass should have the same
declaration signature such as parameters list, type, and return type.
class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
SREZ
Page 29
Object Oriented Programming -I B.E.4th
In the above example, you can see that even though b is a type of Animal it runs the move
method in the Dog class.
The reason for this is: In compile time, the check is made on the reference type. However,
in the runtime, JVM figures out the object type and would run the method that belongs to
that particular object.
Therefore, in the above example, the program will compile properly since Animal class
has the method move. Then, at the runtime, it runs the method specific for that object.
SREZ
Page 30
Object Oriented Programming -I B.E.4th
1 error
This program will throw a compile time error since b's reference type Animal doesn't have a
method by the name of bark.
class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
public void move()
{
super.move(); // invokes the super class method
SREZ
Page 31
Object Oriented Programming -I B.E.4th
Output
Animals can move
Dogs can walk and run
Dynamic Binding
Dynamic binding refers to the process in which linking between method call and method
implementation is resolved at run time (or, a process of calling an overridden method at
run time).
Dynamic binding is also known as run-time polymorphism or late binding. Dynamic
binding uses objects to resolve binding.
Characteristics of Java Dynamic Binding
Linking − Linking between method call and method implementation is resolved at run
time.
Resolve mechanism − Dynamic binding uses object type to resolve binding.
Example − Method overriding is the example of Dynamic binding.
Type of Methods − Virtual methods use dynamic binding.
Example
In this example, we've created two classes Animal and Dog where Dog class extends Animal
class. In main() method, we're using Animal class reference and assign it an object of Dog
class to check Dynamic binding effect.
package com.tutorialspoint;
class Animal
{
public void move()
{
System.out.println("Animals can move");
}
}
{
System.out.println("Dogs can walk and run");
}
}
In the above example, you can see that even though b is a type of Animal it runs the move
method in the Dog class.
The reason for this is: In compile time, the check is made on the reference type. However,
in the runtime, JVM figures out the object type and would run the method that belongs to
that particular object.
Therefore, in the above example, the program will compile properly since Animal class
has the method move. Then, at the runtime, it runs the method specific for that object.
When invoking a superclass version of an overridden method the super keyword is used
so that we can utilize parent class method while using dynamic binding.
Example
In this example, we've created two classes Animal and Dog where Dog class extends Animal
class. Dog class overrides the move method of its super class Animal. But it calls parent
move() method using super keyword so that both move methods are called when child
method is called due to dynamic binding. In main() method, we're using Animal class
reference and assign it an object of Dog class to check Dynamic binding effect.
class Animal
{
public void move()
{
System.out.println("Animals can move");
}
SREZ
Page 33
Object Oriented Programming -I B.E.4th
}
class Dog extends Animal
{
public void move()
{
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog
{
public static void main(String args[])
{
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run
In this example, we've created a Calculator class having two static methods with same name
but different arguments to add two and three int values respectively. In main() method, we're
calling these methods and printing the result. Based on the number of arguments passed,
compiler decides the method using static binding which method is to be called and result is
printed accordingly.
package com.tutorialspoint;
class Calculator
{
public static int add(int a, int b)
{
return a + b;
SREZ
Page 34
Object Oriented Programming -I B.E.4th
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}
Output
60
150
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares
the instance with type. It returns either true or false. If we apply the instanceof operator
with any variable that has null value, it returns false.
Example
class Simple
{
public static void main(String args[])
{
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Output
true
Casting Objects
A cast, instructs the compiler to change the existing type of an object reference to another
type.
In Java, all casting will be checked both during compilation and during execution to
ensure that they are legitimate.
SREZ
Page 35
Object Oriented Programming -I B.E.4th
1. `add(E element)`: Adds the specified element to the end of the list.
```java
ArrayList<String> list = new ArrayList<>();
list.add("apple");
```
2. `add(int index, E element)`: Inserts the specified element at the specified position in
the list.
```java
list.add(1, "banana");
```
SREZ
Page 36
Object Oriented Programming -I B.E.4th
3. `remove(Object obj)`: Removes the first occurrence of the specified element from
the list.
```java
list.remove("apple");
```
4. `remove(int index)`: Removes the element at the specified position in the list.
```java
list.remove(0);
```
5. `get(int index)`: Returns the element at the specified position in the list.
```java
String fruit = list.get(0);
```
6. `set(int index, E element)`: Replaces the element at the specified position in the list
with the specified element.
```java
list.set(0, "orange");
```
```java
int size = list.size();
```
```java
list.clear();
```
```java
boolean empty = list.isEmpty();
```
10. `contains(Object obj)`: Returns true if the list contains the specified element.
```java
boolean contains = list.contains("apple");
SREZ
Page 37
Object Oriented Programming -I B.E.4th
```
11. `indexOf(Object obj)`: Returns the index of the first occurrence of the specified
element in the list, or -1 if the list does not contain the element.
```java
int index = list.indexOf("banana");
```
12. `lastIndexOf(Object obj)`: Returns the index of the last occurrence of the specified
element in the list, or -1 if the list does not contain the element.
```java
int lastIndex = list.lastIndexOf("banana");
```
These are some of the most commonly used methods of the `ArrayList` class in Java.
There are other methods available as well for various purposes.
In Java, `protected` is one of the four access modifiers used to control the visibility of
classes, methods, and variables.
When a member (field or method) is declared `protected`, it can be accessed by classes in
the same package and by subclasses (regardless of whether they are in the same package
or different packages).
```java
package com.example.package1;
```java
package com.example.package2;
import com.example.package1.Parent;
SREZ
Page 38
Object Oriented Programming -I B.E.4th
2. Protected Methods:
A `protected` method can be accessed within the same package and by subclasses, even if
they are in different packages.
Other classes outside the package (which are not subclasses) cannot access the `protected`
method directly.
```java
package com.example.package1;
```java
package com.example.package2;
import com.example.package1.Parent;
In summary, `protected` allows access to members within the same package and by
subclasses, enabling a level of encapsulation while still allowing for inheritance and
extension of functionality.
SREZ
Page 39
Object Oriented Programming -I B.E. 4th
CONCEPT OF EXCEPTION
WHAT IS AN EXCEPTION?
o An exception is an unwanted or unexpected event, which occurs
o during the execution of a program i.e at run time, that disrupts
o the normal flow of the program’s instructions.
WHY AN EXCEPTION OCCURS?
o There can be several reasons that can cause a program to throw
o exception. For example: Opening a non-existing file in your
o program, Network connection problem, bad input data provided by user etc .
EXCEPTION HANDLED BY 5 KEYWORDS:
1. TRY
2. CATCH
3. THROW
4. THROWS
5. FINALLY
EXAMPLE OF EXCEPTION:
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
} catch (ArithmeticException e)
{
System.out.println("ArithmeticException => " + e.getMessage());s
}
}
}
SREZ Page 1
Object Oriented Programming -I B.E. 4th
1. Missing Semicolon
2. Wrong Spelling of keywords and identifiers
3. Missing brackets of class and methods
4. Missing double quotes in the string
5. Use of undeclared Variables.
6. Use of = instead of ==
7. Incompatible types in assignment statements
8. Illegal references to the object
TRY-CATCH BLOCK
syntax:
try
{
//Exception gets generated here
}
catch (ExceptionType name)
{
//Exception is handled here
}
SREZ Page 2
Object Oriented Programming -I B.E. 4th
Example
Syntax
try
{
statement;
try
{
statement ;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Example
SREZ Page 3
Object Oriented Programming -I B.E. 4th
try {
// Inner try block
result = numbers[4]; // Accessing an index out of bounds
} catch (ArrayIndexOutOfBoundsException innerException) {
// Catching and handling ArrayIndexOutOfBoundsException
System.out.println("Inner catch block: Index out of bounds.");
result = numbers[numbers.length - 1]; // Assigning a safe value
}
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
Example
package com.tutorialspoint;
SREZ Page 4
Object Oriented Programming -I B.E. 4th
int b = 0;
int c = 1/b;
System.out.println("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException thrown :" + e);
}catch (Exception e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Output
Exception thrown :java.lang.ArithmeticException: / by zero
Out of the block
Using Throws
According to the Java Compiler - "we mus teither catch checked exceptions by
providing appropriate try-catch block or we should declare them, using throws."
Hence, when a method doesn't want to catch/handle one or more checked exceptions by
providing an appropriate try-catch block within, it must use throws keyword in its
method signature to declare that it does not handle but only throws such checked
exceptions.
Syntax
1)
//Declaring one checked exception using throws keyword
2)
method_name(parameter_list)throws
exception_list
{}
Example
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
SREZ Page 5
Object Oriented Programming -I B.E. 4th
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output
exception handled
normal flow...
Using throw
you may use the throw keyword when you explicitly want to throw an exception.
The keyword throw is followed by an object of the exception class that you want to
throw.
Using throw keyword, an exception can be explicitly thrown from within the
two places in a Java program -
o try block or
o catch blcok.
}
Throw in Catch Block
To throw an exception out of catch block, keyword throw is followed by object reference of
the exception class that was caught by catch block.
For example -
catch(IOException io)
{
throw io; // An existing exception
class object referenced by "io" of type
"IOException", is thrown.
SREZ Page 6
Object Oriented Programming -I B.E. 4th
Finally Clause
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
SREZ Page 7
Object Oriented Programming -I B.E. 4th
Example
package com.tutorialspoint;
Build In Exceptions
Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available.
Checked Exceptions: The checked exceptions are handled by the programmer during
writing the code, they can be handled using the try-catch block. These exceptions are checked
at compile-time.
Unchecked Exceptions: The unchecked exceptions are not handled by the programmer.
These exceptions are thrown on run-time. Some of the unchecked exceptions are
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc.
SREZ Page 8
Object Oriented Programming -I B.E. 4th
SREZ Page 9
Object Oriented Programming -I B.E. 4th
Throwable Class
The java.lang.Throwable class is the superclass of all errors and exceptions in the Java
language.
Only objects that are instances of this class (or one of its subclasses) are thrown by the
Java Virtual Machine or can be thrown by the Java throw statement.
Class Declaration
public class Throwable
extends Object
implements Serializable
Re-throwing Exception:
An exception can be rethrown in a catch block. This action will cause the exception to be
passed to the calling method.
If the rethrow operation occurs in the main method then the exception is passed to the
JVM and displayed on the console.
The purpose of the rethrow operation is to get the attention of the outside world that an
exception has occurred and at the same time perform any contingency logic (such as
logging) in the catch block.
Example
SREZ Page 10
Object Oriented Programming -I B.E. 4th
Chained Exception
➔ Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
➔ For example, consider a situation division operation a/b in which a b is 0 which
throws an ArithmeticException because of an attempt to divide by zero but the actual
cause of exception was an I/O error (bcz wrong input value to variable b)which
caused the divisor to be zero. The method will throw only ArithmeticException to the
caller. So the caller would not come to know about the actual cause of exception.
Chained Exception is used in such type of situations.
The throwable class supports chained exception using the following methods:
Constructors
1. Throwable(Throwable cause) - the cause is the current exception.
2. Throwable(String msg, Throwable cause) - msg is the exception message, the
cause is the current exception.
Methods
1. getCause - returns actual cause.
2. initCause(Throwable cause) - sets the cause for calling an exception.
Example
SREZ Page 11
Object Oriented Programming -I B.E. 4th
IO
SREZ Page 12
Object Oriented Programming -I B.E. 4th
➔ A File object is created by passing in a String that represents the name of a file, or a
String or another File object. For example,
File a = new File("/usr/local/bin/geeks");
➔ defines an abstract file name for the geeks file in directory /usr/local/bin. This is an
absolute abstract file name.
Absolute Path
➔ Simply, a path is absolute if it starts with the root element of the file system. In
windows, the root element is a drive e.g. C:\\, D:\\, while in unix it is denoted by “/”
character.
➔ An absolute path is complete in that no other information is required to locate the file,
it usually holds the complete directory list starting from the root node of the file
system till reaching the file or directory it denotes.
➔ Since absolute path is static and platform dependent, it is a bad practice to locate a file
using absolute path inside your program, since you will lose the ability to reuse your
program on different machines and platforms.
Relative Path
➔ A relative path is a path which doesn’t start with the root element of the file system. It
is simply the path needed in order to locate the file from within the current directory
of your program. It is not complete and needs to be combined with the current
directory path in order to reach the requested file.
➔ In order to construct a rigid and platform independent program, it is a common
convention to use a relative path when locating a file inside your program.
Constructor:
➔ File(File parent, String child) : Creates a new File instance from a parent
abstract pathname and a child pathname string.
➔ File(String parent, String child) : Creates a new File instance from a parent
pathname string and a child pathname string.
➔ File(URI uri) : Creates a new File instance by converting the given file: URI into
an abstract pathname.
Methods:
SREZ Page 13
Object Oriented Programming -I B.E. 4th
1. String getName() : Returns the name of the file or directory denoted by this abstract
pathname.
2. String getParent() : Returns the pathname string of this abstract pathname’s parent.
3. File getParentFile() : Returns the abstract pathname of this abstract pathname’s parent.
4. String getPath() : Converts this abstract pathname into a pathname string.
5. boolean isDirectory() : Tests whether the file denoted by this pathname is a directory.
6. boolean isFile() : Tests whether the file denoted by this abstract pathname is a normal file.
7. boolean canExecute() : Tests whether the application can execute the file denoted by this
abstract pathname.
8. boolean canRead() : Tests whether the application can read the file denoted by this
abstract pathname.
9. boolean canWrite() : Tests whether the application can modify the file denoted by this
abstract pathname.
Output
SREZ Page 14
Object Oriented Programming -I B.E. 4th
Protocol: A protocol defines the set of rules for communication. In the above URL, the https
is a protocol.
Server name or IP Address: Server name or domain name or IP address is the particular
address of a Host. In the above example, www.javatpoint.com is the server name.
Example
package com.javatpoint;
import java.net.*;
public class URLExample {
public static void main(String[] args){
try{
URL url=new URL("https://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());// Using getProtocol() method of the
URL class
System.out.println("Host Name: "+url.getHost()); // Using getHost() method
System.out.println("Port Number: "+url.getPort()); // Using getPort() method
System.out.println("File Name: "+url.getFile()); //Using getFile() method
}
catch(Exception e)
{
System.out.println(e);}
}
}
Output:
Protocol: https
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
Constructor in URL
SREZ Page 15
Object Oriented Programming -I B.E. 4th
➔ URL(String protocol, String host, String file): Creates a URL object from the specified
protcol, host, and file name.
➔ URL(String protocol, String host, int port, String file): Creates a URL object from
protocol, host, port and file name.
➔ URL(URL context, String spec): Creates a URL object by parsing the given spec in the
given context.
➔ URL(String protocol, String host, int port, String file, URLStreamHandler handler):-
Creates a URL object from the specified protocol, host, port number, file, and handler.
Methods in URL
➔ public String getHost(): return the hostname of the URL in IPv6 format.
➔ public String getFile(): returns the file name.
➔ public int getPort(): returns the port associated with the protocol specified by the URL.
➔ public int getDefaultPort: returns the default port used.
➔ public String getProtocol(): returns the protocol used by the URL.
➔ public String toString(): As in any class, toString() returns the string representation of the
given URL object.
➔ public String getAuthority(): returns the authority part of URL or null if empty.
➔ public String getPath(): returns the path of the URL, or null if empty.
➔ The Java URLConnection class represents a communication link between the URL
and the application. This class can be used to read and write data to the specified
resource referred by the URL.
➔ How to get the object of URLConnection class
➔ The openConnection() method of URL class returns the object of URLConnection
class. Syntax:
public URLConnection openConnection()throws IOException{}
SREZ Page 16
Object Oriented Programming -I B.E. 4th
Abstract Classes:
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods.
It needs to be extended and its method implemented. It cannot be instantiated.
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know
the internal processing about the message delivery.
Points to Remember:
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the
method.
Example
abstract class A{}
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example
abstract void printStatus();
SREZ Page 17
Object Oriented Programming -I B.E. 4th
Example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output
running safely
SREZ Page 18
Object Oriented Programming -I B.E. 4th
Interfaces
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction.
There can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
interface <interface_name>{
// by default.
syntax:
SREZ Page 19
Object Oriented Programming -I B.E. 4th
Example
interface printable{
void print();
obj.print();
Output:
Hello
Extending Interfaces
An interface can extend another interface in the same way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits
the methods of the parent interface.
Syntax:
Interface Interface_name2 extends Interface_name1
{
//body of interface
}
Example:
Interface A
{
Int val=10;
}
Interface B extends A
{
Void print_val();
}
Interface A
{
Int val=10;
}
Interface B extends A
SREZ Page 20
Object Oriented Programming -I B.E. 4th
{
Void print_val();
}
interfaces C extends A,B{
…...
}
Comparable Interface
Java Comparable interface is used to order the objects of the user-defined class. This
interface is found in java.lang package and contains only one method named
compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the
elements on the basis of single data member only. For example, it may be rollno, name,
age or anything else.
If we use Arrays and List objects then these objects can be sorted automatically by
Collection.sort method which is basically implements comparable interfaces.
public int compareTo(Object obj): It is used to compare the current object with the
specified object. It returns
● positive integer, if the current object is greater than the specified object.
● negative integer, if the current object is less than the specified object.
● zero, if the current object is equal to the specified object.
Cloneable Interface
The object cloning is a way to create exact copy of an object. The clone() method of
Object class is used to clone an object.
SREZ Page 21
Object Oriented Programming -I B.E. 4th
The java.lang.Cloneable interface must be implemented by the class whose object clone
we want to create. If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.
Does clone object and original object point to the same location in memory
The answer is no. The clone object has its own space in the memory where it copies the
content of the original object. That’s why when we change the content of original object
after cloning, the changes does not reflect in the clone object. Lets see this with the help of
an example.
Example
// Implementing Cloneable interface
class MyClass implements Cloneable {
private int number;
private String text;
// Constructor
public MyClass(int number, String text) {
this.number = number;
this.text = text;
}
SREZ Page 22
Object Oriented Programming -I B.E. 4th
// Output
System.out.println("Original: Number=" + original.getNumber() + ", Text=" +
original.getText());
System.out.println("Cloned: Number=" + cloned.getNumber() + ", Text=" +
cloned.getText());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
Output
Original: Number=10, Text=Original
Cloned: Number=20, Text=Cloned
NEXT PAGE.
SREZ Page 23
Object Oriented Programming -I B.E. 4th
SREZ Page 24
Object Oriented Programming -I B.E. 4th
What is JavaFX?
JavaFX is a Java library used to develop Desktop applications as well as Rich Internet
Applications (RIA). The applications built in JavaFX, can run on multiple platforms
including Web, Mobile and Desktops.
JavaFX is intended to replace swing in Java applications as a GUI framework.
However, It provides more functionalities than swing. Like Swing, JavaFX also
provides its own components and doesn't depend upon the operating system. It is
lightweight and hardware accelerated. It supports various operating systems including
Windows, Linux and Mac OS.
JavaFX application is divided hierarchically into three main components known as Stage,
Scene and nodes.
We need to import javafx.application.Application class in every JavaFX application.
This provides the
following life cycle methods for JavaFX application.
o public void init()
o public abstract void start(Stage primaryStage)
o public void stop()
in order to create a basic JavaFX application, we need to:
1. Import javafx.application.Application into our code.
2. Inherit Application into our class.
3. Override start() method of Application class.
Stage
Stage in a JavaFX application is similar to the Frame in a Swing Application. It acts like
a container for all the JavaFX objects.
Primary Stage is created internally by the platform. Other stages can further be created by
the application. The object of primary stage is passed to start method.
We need to call show method on the primary stage object in order to show our primary
stage. Initially, the primary Stage looks like following.
SREZ Page 1
Object Oriented Programming -I B.E. 4th
Scene
Scene actually holds all the physical contents (nodes) of a JavaFX application.
Javafx.scene.Scene class provides all the methods to deal with a scene object.
Creating scene is necessary in order to visualize the contents on the stage.
At one instance, the scene object can only be added to one stage. In order to implement
Scene in our JavaFX application, we must import javafx.scene package in our code. The
Scene can be created by creating the Scene class object and passing the layout object into
the Scene class constructor. We will discuss Scene class and its method later in detail.
Scene Graph
Scene Graph exists at the lowest level of the hierarchy. It can be seen as the collection of
various nodes. A node is the element which is visualized on the stage. It can be any
button, text box, layout, image, radio button, check box, etc.
The nodes are implemented in a tree kind of structure. There is always one root in the
scene graph. This will act as a parent node for all the other nodes present in the scene
graph. However, this node may be any of the layouts available in the JavaFX system.
The leaf nodes exist at the lowest level in the tree hierarchy. Each of the node present in
the scene graphs represents classes of javafx.scene package therefore we need to import
the package into our application in order to create a full featured javafx application.
To create a JavaFX application, you need to instantiate the Application class and implement
its abstract method start(). In this method, we will write the code for the JavaFX Application.
Application Class
The Application class of the package javafx.application is the entry point of the application in
JavaFX. To create a JavaFX application, you need to inherit this class and implement its
SREZ Page 2
Object Oriented Programming -I B.E. 4th
abstract method start(). In this method, you need to write the entire code for the JavaFX
graphics
In the main method, you have to launch the application using the launch() method. This
method internally calls the start() method of the Application class as shown in the following
program.
Within the start() method, in order to create a typical JavaFX application, you need to follow
the steps given below −
Example
The following program generates an empty JavaFX window. Save this code in a file with the
name JavafxSample.java
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
SREZ Page 3
Object Oriented Programming -I B.E. 4th
javac JavafxSample.java
java JavafxSample
import javafx.application.Application;
SREZ Page 4
Object Oriented Programming -I B.E. 4th
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
@Override
circle.setStyle("-fx-fill: skyblue;");
stackPane.getChildren().addAll(circle, button);
primaryStage.setScene(scene);
primaryStage.setTitle("Simple Example");
primaryStage.show();
SREZ Page 5
Object Oriented Programming -I B.E. 4th
Property Binding
JAVAFX introduces a new concept called property binding that enables a target object to
be bound to a source object.
The target object is simply called a binding object or a binding property.
Method:
target.bind(source)
In JavaFX, we can fill the shapes with the colors. We have the flexibility to create our
own color using the several methods and pass that as a Paint object into the setFill()
method. Let's discuss the several methods of creating color in JavaFX.
RGB Color
RGB color system is the most popular method to create a color in graphics. It consists of
three components named as RED → R, GREEN → G and BLUE → B. Each component
uses 8 Bits that means every component can have the integer value from 0
SREZ Page 6
Object Oriented Programming -I B.E. 4th
to 22^8 - 1=255.
The computer screen can be seen as the collection of pixels. The set (R,G,B) actually
represents the emission of their respective LEDs on the screen.
If the value of RED is set to 0 then it means that the Red LED is turned off while the
value 255 indicates that the full emission of LED is being there. The combination of
(0,0,0) represents the black color while (255,255,255) represents the white color. The
middle values in that range can represent different colors.
Using the superimposition of RGB, we can represent 255*255*255 different colors.
In JavaFX, the class javafx.scene.paint.Color class represents colors.
There is a static method named as rgb() of Color class. It accepts three integer
arguments as Red, Green, Blue and one optional double argument called alpha. The
value of alpha is proportional to the opacity of the color. The alpha value 0 means that
the color is completely transparent while the value 1 means that the color is
completely opaque.
Example
package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Shadow;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
@Override
primarystage.setTitle("Color Example");
rect.setX(50);
rect.setY(20);
SREZ Page 7
Object Oriented Programming -I B.E. 4th
rect.setWidth(100);
rect.setHeight(150);
int red=20;
int green=125;
int blue=10;
root.getChildren().add(rect);
primarystage.setScene(scene);
primarystage.show();
launch(args);
} Output
we need to provide the text based information on the interface of our application. JavaFX
library provides a class named javafx.scene.text.Text for this purpose. This class provides
various methods to alter various properties of the text. We just need to instantiate this class to
implement text in our application.
SREZ Page 8
Object Oriented Programming -I B.E. 4th
Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
@Override
SREZ Page 9
Object Oriented Programming -I B.E. 4th
root.getChildren().add(text);
primaryStage.setScene(scene);
primaryStage.setTitle("Text Example");
primaryStage.show();
launch(args);
Output
JavaFX enables us to apply various fonts to the text nodes. We just need to set the
property font of the Text class by using the setter method setFont(). This method
accepts the object of Font class.
The class Font belongs the package javafx.scene.text. It contains a static method
named font(). This returns an object of Font type which will be passed as an argument
into the setFont() method of Text class. The method Font.font() accepts the following
parameters.
Family: it represents the family of the font. It is of string type and should be an
appropriate font family present in the system.
Weight: this Font class property is for the weight of the font. There are 9 values which
can be used as the font weight. The values are FontWeight. BLACK, BOLD,
EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD,
THIN.
SREZ Page 10
Object Oriented Programming -I B.E. 4th
Posture: this Font class property represents the posture of the font. It can be either
FontPosture.ITALIC or FontPosture.REGULAR.
Size: this is a double type property. It is used to set the size of the font. The Syntax of the
method setFont() is given below.
<text_object>.setFont(Font.font(<String font_family>, <FontWeight>, <FontPosture>,
<FontSize>)
Example
package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextExample extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Text text = new Text();
text.setX(100);
text.setY(20);
text.setFont(Font.font("Abyssinica SIL",FontWeight.BOLD,FontPosture.REGULAR,20));
text.setText("Welcome to Java");
Group root = new Group();
Scene scene = new Scene(root,500,200);
root.getChildren().add(text);
primaryStage.setScene(scene);
primaryStage.setTitle("Text Example");
primaryStage.show();
}
publicstaticvoid main(String[] args) {
launch(args);
}
}
Output
SREZ Page 11
Object Oriented Programming -I B.E. 4th
You can load and modify images using the classes provided by JavaFX in the package
javafx.scene.image. JavaFX supports the image formats like Bmp, Gif, Jpeg, Png.
Loading an Image
You can load an image in JavaFX by instantiating the class named Image of the
package javafx.scene.image.
To the constructor of the class, you have to pass either of the following −
● An InputStream object of the image to be loaded or,
● A string variable holding the URL for the image.
After loading the image, you can set the view for the image by instantiating the
ImageView class and passing the image to its constructor as follows −
Example
SREZ Page 12
Object Oriented Programming -I B.E. 4th
Layout Panes:
Layouts are the top level container classes that define the UI styles for scene graph
objects. Layout can be seen as the parent node to all the other nodes. JavaFX provides
various layout panes that support different styles of layouts.
In JavaFX, Layout defines the way in which the components are to be seen on the stage.
It basically organizes the scene-graph nodes. We have several built-in layout panes in
JavaFX that are HBox, VBox, StackPane, FlowBox, AnchorPane, etc.
Each Built-in layout is represented by a separate class which needs to be instantiated in
order to implement that particular layout pane.
All these classes belong to javafx.scene.layout package. javafx.scene.layout.Pane class
is the base class for all the built-in layout classes in JavaFX.
Layout Classes:
javafx.scene.layout Package provides various classes that represents the layouts. The
classes are described in the table below.
SREZ Page 13
Object Oriented Programming -I B.E. 4th
HBox
HBox Constructor:
The HBox class contains two constructors that are given below.
1. new HBox() : create HBox layout with 0 spacing
2. new Hbox(Double spacing) : create HBox layout with a spacing value
Example
SREZ Page 14
Object Oriented Programming -I B.E. 4th
VBox
Instead of arranging the nodes in horizontal row, Vbox Layout Pane arranges the nodes in
a single vertical column.
It is represented by javafx.scene.layout.VBox class which provides all the methods to
deal with the styling and the distance among the nodes.
This class needs to be instantiated in order to implement VBox layout in our application.
VBox Constructors:
Example
SREZ Page 15
Object Oriented Programming -I B.E. 4th
JavaFX StackPane
The StackPane layout pane places all the nodes into a single stack where every new node
gets placed on the top of the previous node. It is represented by
javafx.scene.layout.StackPane class. We just need to instantiate this class to implement
StackPane layout into our application
The class contains two constructors that are given below.
1. StackPane()
2. StackPane(Node? Children)
.
Example
GridPane:
GridPane Layout pane allows us to add the multiple nodes in multiple rows and
columns. It is seen as a flexible grid of rows and columns where nodes can be placed
in any cell of the grid. It is represented by javafx.scence.layout.GridPane class. We
just need to instantiate this class to implement GridPane.
The class contains only one constructor that is given below
Public GridPane(): creates a gridpane with 0 hgap/vgap.
SREZ Page 16
Object Oriented Programming -I B.E. 4th
Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Label first_name=new Label("First Name");
Label last_name=new Label("Last Name");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button Submit=new Button ("Submit");
GridPane root=new GridPane();
Scene scene = new Scene(root,400,200);
root.addRow(0, first_name,tf1);
root.addRow(1, last_name,tf2);
root.addRow(2, Submit);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output
SREZ Page 17
Object Oriented Programming -I B.E. 4th
JavaFX FlowPane
FlowPane layout pane organizes the nodes in a flow that are wrapped at the flowpane's
boundary.
The horizontal flowpane arranges the nodes in a row and wrap them according to the
flowpane's width.
The vertical flowpane arranges the nodes in a column and wrap them according to the
flowpane's heigh FlowPane layout is represented by javafx.scene.layout.FlowPane class.
We just need to instantiate this class to create the flowpane layout.
Constructors
There are 8 constructors in the class that are given below.
1. FlowPane()
2. FlowPane(Double Hgap, Double Vgap)
3. FlowPane(Double Hgap, Double Vgap, Node? children)
4. FlowPane(Node... Children)
5. FlowPane(Orientation orientation)
6. FlowPane(Orientation orientation, double Hgap, Double Vgap)
7. FlowPane(Orientation orientation, double Hgap, Double Vgap, Node? children )
8. FlowPane(Orientation orientation, Node... Children)
Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class FlowPaneTest extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("FlowPane Example");
SREZ Page 18
Object Oriented Programming -I B.E. 4th
BorderPane
BorderPane arranges the nodes at the left, right, centre, top and bottom of the screen.
It is represented by javafx.scene.layout.BorderPane class. This class provides
various methods like setRight(), setLeft(), setCenter(), setBottom() and setTop()
which are used to set the position for the specified nodes
We need to instantiate BorderPane class to create the BorderPane layout.
There are the following constructors in the class.
○ BorderPane() : create the empty layout
○ BorderPane(Node Center) : create the layout with the center node
○ BorderPane(Node Center, Node top, Node right, Node bottom, Node left) :
create the layout with all the nodes
Properties
SREZ Page 19
Object Oriented Programming -I B.E. 4th
Constructors
There are the following constructors in the class.
1. BorderPane() : create the empty layout
2. BorderPane(Node Center) : create the layout with the center node
3. BorderPane(Node Center, Node top, Node right, Node bottom, Node left) : create the
layout with all the nodes
Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output
SREZ Page 20
Object Oriented Programming -I B.E. 4th
Shapes
In some of the applications, we need to show two dimensional shapes to the user.
However, JavaFX provides the flexibility to create our own 2D shapes on the screen .
There are various classes which can be used to implement 2D shapes in our
application. All these classes resides in javafx.scene.shape package.
This package contains the classes which represents different types of 2D shapes.
There are several methods in the classes which deals with the coordinates regarding
2D shape creation.
Line:
In general, Line can be defined as the geometrical structure which joins two points
(X1,Y1) and (X2,Y2) in a X-Y coordinate plane. JavaFX allows the developers to
create the line on the GUI of a JavaFX application. JavaFX library provides the class
Line which is the part of javafx.scene.shape package.
How to create a Line?
Follow the following instructions to create a Line.
o Instantiate the class javafx.scene.shape.Line.
o set the required properties of the class object.
o Add class object to the group
Properties:
Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class LineDrawingExamples extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Line line = new Line(); //instantiating Line class
line.setStartX(0); //setting starting X point of Line
line.setStartY(0); //setting starting Y point of Line
line.setEndX(100); //setting ending X point of Line
line.setEndY(200); //setting ending Y point of Line
SREZ Page 21
Object Oriented Programming -I B.E. 4th
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Rectangle:
In general, Rectangles can be defined as the geometrical figure consists of four sides, out
of which, the opposite sides are always equal and the angle between the two adjacent
sides is 90 degree. A Rectangle with four equal sides is called square.
JavaFX library allows the developers to create a rectangle by instantiating
javafx.scene.shape.Rectangle class
Example
package application;
import javafx.application.Application;
import javafx.scene.Group;
SREZ Page 22
Object Oriented Programming -I B.E. 4th
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Shape_Example extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Rectangle Example");
Group group = new Group(); //creating Group
Rectangle rect=new Rectangle(); //instantiating Rectangle
rect.setX(20); //setting the X coordinate of upper left //corner of rectangle
rect.setY(20); //setting the Y coordinate of upper left //corner of rectangle
rect.setWidth(100); //setting the width of rectangle
rect.setHeight(100); // setting the height of rectangle
group.getChildren().addAll(rect); //adding rectangle to the //group
Scene scene = new Scene(group,200,300,Color.GRAY);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Circle:
A circle is a special type of ellipse with both of the focal points at the same position. Its
horizontal radius is equal to its vertical radius. JavaFX allows us to create Circle on the GUI
of any application by just instantiating javafx.scene.shape.Circle class. Just set the class
properties by using the instance setter methods and add the class object to the Group.
SREZ Page 23
Object Oriented Programming -I B.E. 4th
package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Shape_Example extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Circle Example");
Group group = new Group();
Circle circle = new Circle();
circle.setCenterX(200);
circle.setCenterY(200);
circle.setRadius(100);
circle.setFill(Color.RED);
group.getChildren().addAll(circle);
Scene scene = new Scene(group,400,500,Color.GRAY);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output
SREZ Page 24
Object Oriented Programming -I B.E. 4th
Ellipse :
In general, ellipse can be defined as the geometrical structure with the two focal points.
The focal points in the ellipse are chosen so that the sum of the distance to the focal
points is constant from every point of the ellipse.
In JavaFX, the class javafx.scene.shape.Ellipse represents Ellipse. This class needs to be
instantiated in order to create ellipse. This class contains various properties which needs
to be set in order to render ellipse on a XY place.
Example
package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;
public class Shape_Example extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Ellipse Example");
Group group = new Group();
Ellipse elipse = new Ellipse();
elipse.setCenterX(100);
elipse.setCenterY(100);
elipse.setRadiusX(50);
elipse.setRadiusY(80);
group.getChildren().addAll(elipse);
Scene scene = new Scene(group,200,300,Color.GRAY);
primaryStage.setScene(scene);
primaryStage.show();
SREZ Page 25
Object Oriented Programming -I B.E. 4th
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Arc
In general, Arc is the part of the circumference of a circle or ellipse. It needs to be created in
some of the JavaFX applications wherever required. JavaFX allows us to create the Arc on
GUI by just instantiating javafx.scene.shape.Arc class. Just set the properties of the class to
the appropriate values to show arc as required by the Application.
Example
package application;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.stage.Stage;
public class Shape_Example extends Application{
SREZ Page 26
Object Oriented Programming -I B.E. 4th
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Arc Example");
Group group = new Group();
Arc arc = new Arc();
arc.setCenterX(100);
arc.setCenterY(100);
arc.setRadiusX(50);
arc.setRadiusY(80);
arc.setStartAngle(30);
arc.setLength(70);
arc.setType(ArcType.ROUND);
arc.setFill(Color.RED);
group.getChildren().addAll(arc);
Scene scene = new Scene(group,200,300,Color.GRAY);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Polygons:
Polygon can be defined as a plain figure with at least three straight sides forming a loop.
In the case of polygons, we mainly considers the length of its sides and the interior
angles. Triangles, squares, Pentagons, Hexagons,etc are all polygons.
In JavaFX, Polygon can be created by instantiating javafx.scene.shape.Polygon class.
We need to pass a Double array into the class constructor representing X-Y coordinates of
all the points of the polygon.
The syntax is given below.
Polygon poly = new Polygon(DoubleArray);
We can also create polygon by anonymously calling addAll() method on the reference
returned by calling getPoints() method which is an instance method of Polygon class.
However, we need to pass the double array into this method, which represents X-Y
coordinates of the polygon. The syntax is given below.
Pollygon polygon_object = new Pollygon();
Pollygon_Object.getPoints().addAll(Double_Array);
SREZ Page 27
Object Oriented Programming -I B.E. 4th
Example
Event Source Object: The object generates the event is called event source
object .
For Example: if the event gets generated on clicking the button, then
button is the event source object.
Event Handler: The event handling code written to process the generated
event is called event handler.
Types of Events
1. Foreground Events
Foreground events are mainly occur due to direct interaction of the user with the GUI of the
application.
SREZ Page 28
Object Oriented Programming -I B.E. 4th
. Such as clicking the button, pressing a key, selecting an item from the list, scrolling the
page, etc.
2. Background Events
Background events doesn't require the user's interaction with the application. These events
are mainly occurred to the operating system interrupts, failure, operation completion, etc.
SREZ Page 29
Object Oriented Programming -I B.E. 4th
Example
Inner Classes:
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
Additionally, it can access all the members of outer class including private data members
and methods.
Syntax:
Acess_modifier class Java_Outer_class
{
//code
Acess_modifier class Java_Inner_class
{
//code
}
}
SREZ Page 30
Object Oriented Programming -I B.E. 4th
A static class i.e. created inside a class is called static nested class in java. It cannot access
non-static data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
A non-static class that is created inside a class but outside a method is called
member inner class.
Syntax:
class Outer{
//code
}
class Inner{
/ /code
}
A class i.e. created inside a method is called local inner class in java. If
you want to invoke the methods of local inner class, you must instantiate
this class inside the method.
SREZ Page 31
Object Oriented Programming -I B.E. 4th
A class that have no name is known as anonymous inner class in java. It should
be used if you have to override method of class or interface. Java Anonymous
inner class can be created by two ways:
1. Class (may be abstract or concrete).
2. Interface
SREZ Page 32
Object Oriented Programming -I B.E. 4th
Lamda Method
Anonymous inner class event handler
ok_button.setOnAction{
new EventHandler <ActionEvent>(){
@override
Public void handle(ActionEvent event)
{
System.out.println(“OK Button is clicked!!!”);
SREZ Page 33
Object Oriented Programming -I B.E. 4th
}
});
ok_button.setOnAction((ActionEvent e)->
{
System.out.println(“OK Button is clicked!!!”);
}
MouseEvent Class
Method Description
MouseButton getButton It represent which mount button is pressed
int getClickCount() It returns the number of mouse clicks.
double getX() It returns the x-coordinates of the mouse
point in the event
source node.
double getY() It returns the y-coordinates of the mouse
point in the event
source node.
double getSceneX() It returns the x-coordinates of the mouse
point in the Scene
double getSceneY() It returns the y-coordinates of the mouse
point in the Scene
double getscreenX() It returns the x-coordinates of the mouse
point in the Screen
double getscreenY() It returns the y-coordinates of the mouse
SREZ Page 34
Object Oriented Programming -I B.E. 4th
Keyboard Events:
When any key on the keyboard is pressed,released,or typed on a node then the
keyboard event
occurs.
SREZ Page 35
Object Oriented Programming -I B.E. 4th
KeyEvent Class
Example
SREZ Page 36
Object Oriented Programming -I B.E. 4th
package javafxapplicationobservable;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
Animation
In general, the animation can be defined as the transition which creates the myth
of motion for an object. It is the set of transformations applied on an object over
the specified duration sequentially so that the object can be shown as it is in
motion.
This can be done by the rapid display of frames. In JavaFX, the package
javafx.animation contains all the classes to apply the animations onto the nodes.
All the classes of this package extend the class javafx.animation.Animation.
JavaFX provides the classes for the transitions like RotateTransition,
ScaleTransition, TranslateTransition, FadeTransition, FillTransition,
StrokeTransition, etc.
SREZ Page 37
Object Oriented Programming -I B.E. 4th
Path Transition
It allows the node to animate through a specified path over the specified
duration. In JavaFX, the path is defined by instantiating the class
javafx.scene.shape.Path.
The translation along this path is done by updating the x and y coordinate
of the node at the regular intervals. The rotation can only be done in the
case when the orientation is set to be
OrientationType.ORTHOGONAL_TO_TANGENT.
In JavaFX, the class javafx.animation.PathTransition represents the
path transition. We need to instantiate this class in order to create an
appropriate path transition.
SREZ Page 38
Object Oriented Programming -I B.E. 4th
Constructor:
SREZ Page 39
Object Oriented Programming -I B.E. 4th
SREZ Page 40
Object Oriented Programming -I B.E. 4th
Fade Transition
It animates the opacity of the node so that the fill color of the node becomes dull. This
can be done by keep decreasing the opacity of the fill color over a specified duration in
order to reach a target opacity value.
In JavaFX, the class javafx.animation.FadeTransition represents Fade Transition. We
need to instantiate this class in order to create the appropriate Fade Transition.
Constructor:
Timeline :
An animation is driven by its associated properties, such as size, location, and color etc.
Timeline provides the capability to update the property values along the progression of
time. JavaFX supports key frame animation.
In key frame animation, the animated state transitions of the graphical scene are declared
by start and end snapshots (key frames) of the state of the scene at certain times. The
system can automatically perform the animation. It can stop, pause, resume, reverse, or
repeat movement when requested.
SREZ Page 41
Object Oriented Programming -I B.E. 4th
Introduction to UI Control
This part of the tutorial provides you the in-depth knowledge of JavaFX UI controls. The
graphical user interface of every desktop application mainly considers UI elements,
layouts and behaviour.
The UI elements are the one which are actually shown to the user for interaction or
information exchange. Layout defines the organization of the UI elements on the screen.
Behaviour is the reaction of the UI element when some event is occurred on it.
However, the package javafx.scene.control provides all the necessary classes for the UI
components like Button, Label, etc. Every class represents a specific UI control and
defines some methods for their styling.
Control Description
Label Label is a component that is used to define a
simple text on the screen. Typically, a label is
placed with the node, it describes.
RadioButton Button is a component that controls the function
of the application. Button class is used to create a
labelled button.
RadioButton The Radio Button is used to provide various
options to the user. The user can only choose one
option among all. A radio button is either selected
or deselected.
CheckBox Check Box is used to get the kind of information
from the user which contains various choices.
User marked the checkbox either on (true) or
off(false).
TextField Text Field is basically used to get the input from
the user in the form of text.
javafx.scene.control.TextField represents
TextField
Textarea This control allows the user to enter multiple
line text.
ComboBox This control display the list of items out of
which user can select at most one item.
ListView This control displays the list of items out of
which user can select one or multiple items
from the list.
Slider This control is used to display a continuous or
discrete range of valid numeric choices and
SREZ Page 1
Object Oriented Programming -I B.E. 4th
Constructors:
1. Label(): creates an empty Label
2. Label(String text): creates Label with the supplied text
3. Label(String text, Node graphics): creates Label with the supplied text and
graphics
Implementation of label
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label my_label=new Label("This is an example of Label");
StackPane root = new StackPane();
Scene scene=new Scene(root,300,300);
root.getChildren().add(my_label);
primaryStage.setScene(scene);
primaryStage.setTitle("Label Class Example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
SREZ Page 2
Object Oriented Programming -I B.E. 4th
Output:
Button
Implementation of button
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
SREZ Page 3
Object Oriented Programming -I B.E. 4th
launch(args);
}
}
Output:
We can wrap the text of the button into multiple lines if the text to be displayed is too
long.
This can be done by calling a setter method setWrapText(boolean) on the instance of
Button class. Pass the boolean value true in the method wherever required.
Btn.setWrapText(true);
CheckBox
The Check Box is used to provide more than one choices to the user. It can be used in a
scenario where the user is prompted to select more than one option or the user wants to
select multiple options.
It is different from the radiobutton in the sense that, we can select more than one
checkboxes in a scenerio.
Instantiate javafx.scene.control.CheckBox class to implement CheckBox.
Use the following line in the code to create a blank CheckBox.
CheckBox checkbox = new CheckBox();
We can change the CheckBox Label at any time by calling an instance method
setText("text"). We can make it selected by calling setSelected("true")
SREZ Page 4
Object Oriented Programming -I B.E. 4th
Implementation of chechkbox
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class CheckBoxTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label l = new Label("What do you listen: ");
CheckBox c1 = new CheckBox("Radio one");
CheckBox c2 = new CheckBox("Radio Mirchi");
CheckBox c3 = new CheckBox("Red FM");
CheckBox c4 = new CheckBox("FM GOLD");
HBox root = new HBox();
root.getChildren().addAll(l,c1,c2,c3,c4);
root.setSpacing(5);
Scene scene=new Scene(root,800,200);
primaryStage.setScene(scene);
primaryStage.setTitle("CheckBox Example");
primaryStage.show();
}
}
Output:
RadioButton
The Radio Button is used to provide various options to the user. The user can only choose
one option among all. A radio button is either selected or deselected.
It can be used in a scenario of multiple choice questions in the quiz where only one option
needs to be chosen by the student.
We can group JAVAFX RadioButton instances into a ToggleGroup.A ToggleGroup
allows at most one RadioButton to be selected at any time.
SREZ Page 5
Object Oriented Programming -I B.E. 4th
Implementation of RadioButton
TextField
Text Field is basically used to get the input from the user in the form of text.
javafx.scene.control.TextField represents TextField. It provides various methods to deal
with textfields in JavaFX.
TextField can be created by instantiating TextField class.
Implementation of TextField
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class TextFieldTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
SREZ Page 6
Object Oriented Programming -I B.E. 4th
TextArea
The TextARea control allows to enter multiline text.
The control is represented by the class javafx.scene.control.TextArea.
SYNTAX:
TextArea ta=new TextArea()
We can set the size of the TextArea using setPrefHeight() and setPrefWidth() functions.
SREZ Page 7
Object Oriented Programming -I B.E. 4th
Combo Box
The JavaFX ComboBox control enables users to choose an option from a predefined list
of choices, or type in another value if none of the predefined choices matches what the
user want to select.
The JavaFX ComboBox control is represented by the class
javafx.scene.control.ComboBox .
This JavaFX ComboBox tutorial will explain how to use the ComboBox class.
SYNTAX:
ComboBox comboBox = new ComboBox();
You can add choices to a ComboBox by obtaining its item collection and add items to it.
Here is an example that adds choices to a JavaFX ComboBox :
cb.getItems().add("Choice 1");
cb.getItems().add("Choice 2");
cb.getItems().add("Choice 3");
Implementation of ComboBox
SREZ Page 8
Object Oriented Programming -I B.E. 4th
ListView
The JavaFX ListView control enables users to choose one or more options from a
predefined list of choices.
The JavaFX ListView control is represented by the class javafx.scene.control.ListView .
This JavaFX ListView tutorial will explain how to use the ListView class.
SYNTAX:
ListView listView = new ListView();
You can add items (options) to a ListView by obtaining its item collection and add items
to it.
Here is an example that adds items to a JavaFX ListView :
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Implementation of ListView
SREZ Page 9
Object Oriented Programming -I B.E. 4th
Scrollbar
JavaFX Scroll Bar is used to provide a scroll bar to the user so that the user can scroll down
the application pages. It can be created by instantiating
javafx.scene.control.ScrollBar class.
implementation of scrollbar
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ScrollBar extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
ScrollBar s = new ScrollBar();
StackPane root = new StackPane();
root.getChildren().add(s);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("ScrollBar Example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
SREZ Page 10
Object Oriented Programming -I B.E. 4th
}
Output:
Slider
JavaFX slider is used to provide a pane of option to the user in a graphical form where the
user needs to move a slider over the range of values to select one of them. Slider can be
created by instantiating javafx.scene.control.Slider class.
The constructor accepts three arguments: the minimum value, the maximum value, and the initial
value of the slider.
Implementation of Slider
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class SliderTest extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Slider slider = new Slider(1,100,20);
StackPane root = new StackPane();
root.getChildren().add(slider);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Slider Example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
SREZ Page 11
Object Oriented Programming -I B.E. 4th
Output:
Video
Playing video in JavaFX is quite simple. We need to use the same API as we have used in
the case of playing Audio files. In the case of playing video, we need to use the
MediaView node to display the video onto the scene.
For this purpose, we need to instantiate the MediaView class by passing the Mediaplayer
object into its constructor. Due to the fact that, MediaView is a JavaFX node, we will be
able to apply effects to it.
In this part of the tutorial, we will discuss the steps involved in playing video media files
and some examples regarding this
Steps to play video files in JavaFX
3. Invoke the MediaPlayer object's play() method when onReady event is triggered.
mediaPlayer.setAutoPlay(true);
4. Instantiate MediaView class and pass Mediaplayer object into its constructor.
MediaView mediaView = new MediaView (mediaPlayer)
Example
package application;
import java.io.File;
import javafx.application.Application;
SREZ Page 12
Object Oriented Programming -I B.E. 4th
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
public class JavaFX_Media Example extends Application
{
@Override
publicvoid start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
//Initialising path of the media file, replace this with your file path
String path = "/home/javatpoint/Downloads/test.mp4";
Audio
We can load the audio files with extensions like .mp3,.wav and .aifff by using JavaFX
Media API. We can also play the audio in HTTP live streaming format. It is the new
feature introduced in JavaFX 8 which is also known as HLS.
Playing audio files in JavaFX is simple. For this purpose, we need to instantiat
javafx.scene.media.Media class by passing the audio file path in its constructor. The
steps required to be followed in order to play audio files are described below.
SREZ Page 13
Object Oriented Programming -I B.E. 4th
1. Instantiate the javafx.scene.media.Media class by passing the location of the audio file in
its constructor.
Use the following line of code for this purpose.
1. Media media = new
Media("http://path/file_name.mp3");
2. Pass the Media class object to the new instance of javafx.scene.media.MediaPlayer
object.
1. Mediaplayer mediaPlayer = new
MediaPlayer(media);
3. Invoke the MediaPlayer object's play() method when onReady event is triggered.
1. MediaPlayer.setAutoPlay(true);
The Media File can be located on a web server or on the local file system. SetAutoPlay()
method is the short-cut for setting the setOnReady() event handler with the lambda
expression to handle the event.
Example
package application;
import java.io.File;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
public class JavaFX_Media Example extends Application
{
@Override
public void start (Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
//Initialising path of the media file, replace this with your file path
String path = "/home/javatpoint/Downloads/test.mp3";
SREZ Page 14