0% found this document useful (0 votes)
6 views113 pages

Java Class and Object Fundamentals

The document provides a comprehensive overview of Java programming concepts, focusing on classes, objects, methods, and polymorphism. It explains the structure of classes, the use of constructors, and the importance of instance variables, along with examples of object initialization and method overloading. Additionally, it discusses the final keyword, built-in methods, and various Java methods for handling numbers and characters.

Uploaded by

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

Java Class and Object Fundamentals

The document provides a comprehensive overview of Java programming concepts, focusing on classes, objects, methods, and polymorphism. It explains the structure of classes, the use of constructors, and the importance of instance variables, along with examples of object initialization and method overloading. Additionally, it discusses the final keyword, built-in methods, and various Java methods for handling numbers and characters.

Uploaded by

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

JAVA

PROGRAMMING

By Deepa sonal
What is a class in Java
● A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical
entity. It can't be physical.
● A class in Java can contain:
● Fields
● Methods
● Constructors
● Blocks
● Nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}
Example:-
Create an object called "myObj" and print the value of x:
public class MyClass {
int x = 5;
public static void main(String[] args) {
MyClass myObj = new MyClass();
[Link](myObj.x);
}}
Class consists of:
Instance variable in Java
● A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created. That is why it is known as an instance variable.
Method in Java
● In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
● Code Reusability
● Code Optimization
new keyword in Java
● The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
Object and Class Example: main within the class

● In this example, we have created a Student class which


has two data members id and name. We are creating the
object of the Student class by new keyword and printing
the object's value.
● Here, we are creating a main() method inside the class.
File: [Link]
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student
{ //defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
//Printing values of the object
[Link]([Link]);//accessing member through reference variable
[Link]([Link]);
}
}

Output:
0 null
Three Ways to initialize object

There are 3 ways to initialize object in Java.


● By reference variable
● By method
● By constructor
1) Object and Class Example: Initialization through reference
● Initializing an object means storing data into the object.
Let's see a simple example where we are going to initialize
the object through a reference variable.
File: [Link]
class Student
{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
[Link]=101;
[Link]="Sonoo";
[Link]([Link]+" "+[Link]);//printing members with a white space
}
}

Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
File: [Link]
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
[Link]=101;
[Link]="Sonoo";
[Link]=102;
[Link]="Amit";
//Printing data
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
}
}
Output:
101 Sonoo 102 Amit
Object and Class Example: Initialization
through method

● In this example, we are creating the two objects of


Student class and initializing the value to these
objects by invoking the insertRecord method. Here,
we are displaying the state (data) of the objects by
invoking the displayInformation() method.
File: [Link]
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
●Let's see an example where
we are maintaining records
of employees.
File: [Link] public class TestEmployee {
class Employee{ public static void main(String[] args) {
int id; Employee e1=new Employee();
String name; Employee e2=new Employee();
float salary; Employee e3=new Employee();
void insert(int i, String n, float s) { [Link](101,"ajeet",45000);
[Link](102,"irfan",25000);
id=i; [Link](103,"nakul",55000);
name=n; [Link]();
salary=s; [Link]();
} [Link]();
void display() }
{[Link](id+" "+name+" "+ }
salary);}
}
OBJECT AND CLASS EXAMPLE: INITIALIZATION THROUGH A
CONSTRUCTOR

Constructor
● In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
● It is a special type of method which is used to initialize the object.
● Every time an object is created using the new() keyword, at least one
constructor is called.
Rules for creating Java constructor

● Constructor name must be the same as its class name


● A Constructor must have no explicit return type
● A Java constructor cannot be abstract, static, final, and synchronized
Example of constructor
public class Student
public class Demo
{
{
int roll;
int roll;
String name; String name;
Demo() Student()
{ {
[Link](“Object is roll=2;
created”); name=“Ram”;
}
}
public static void main(String
args[])
void display()
{ Demo ob=new Demo(); {
}
} [Link](“Roll=“+roll+”Name=“+name);
}
public static void main(String args[])
{ Student ob=new Student();
[Link]();
}
}
public class Student
{
int roll;
String name;
Student(int r,String n)
{
roll=r;
name=n;
}
void display()
{
[Link](“Roll=“+roll+”Name=“+name);
}
public static void main(String args[])
{ Student ob=new Student(2,”Ram");
[Link]();
}
}
Important points

● All object share the same method location.


● Always keep those properties of an object as instance data member whose values are changing for each object.
● Static member allocate memory at class loading time. It will take space inside class initialize. It is the part of class area.
● All object sharing the same memory location of static member.
● All static things are part of class & non-static things are a part of object.
● Static member function can use static and non-static data member or member
function. Static data member or member function call directly by its name or help of
class name or by the help object but non-static data-member or member function
always access by the help of reference variable..
● Non-static member function is never call directly inside static method.
class Demo
{
static void disp()
//int x=10;//Static initialize of non-static data
{
member.
[Link]("Y="+y);
int x;
}
static int y=100;
public static void main(String[]args)
Demo(int n)
{
{
new Demo().show();
x=n;
new Demo().disp();
}
disp();
Demo()
[Link]();
{
[Link](new
x=10;
Demo().x);
}
[Link](new
void show()
Demo(60).x);
{
}
[Link]("X="+x);
}
[Link]("Y="+y);
}
Polymorphism in Java
● Polymorphism in Java is a concept by which we can
perform a single action in different ways. Polymorphism is
derived from two Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So
polymorphism means many forms.
● There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism. We can
perform polymorphism in java by method overloading and
method overriding.
● Normally it has two types:-
● Compile Time:- Compile time occurs when ever an object is bound its
functionality at compile.
● Example:- Function Overloading, Operator Overloading(But java does not
support operator overloading explicitly)

● Run Time:- Run time polymorphism occurs when ever object bound its
functionality at run time.
● Example:- function Overriding
Important Points:-

● Java does not support explicitly operator overloading.


● Java support implicitly operator overloading. Example:- “+”
● By default every method or member function in java are virtual. We know that virtual function
always bind at run time.
● So, java supports only run time polymorphism.
● It never support compile time polymorphism.
● When some specific components able to adjust into different object then it is known as
Polymorphism but when completely any object merge into different object than it is known as
“Generalization”.
● Some book says that private, final and static methods are bind at compile time. But actually java doesn’t
support compile time polymorphism.
Method Overloading in Java

● If a class has multiple methods having same name but different


in parameters, it is known as Method Overloading.
● If we have to perform only one operation, having same name of
the methods increases the readability of the program.
There are two ways to overload the method in java
● By changing number of arguments
For example: add(int, int) add(int, int, int)
● By changing the data type.
For example: add(int, int) add(int, float)
Object as a parameter
● A method can take an objects as a parameter. If we pass an
object as an argument to a method, the mechanism that
applies is called pass-by-reference, because a copy of the
reference contained in the variable is transferred to the
method, not a copy of the object itself.
● For example, in the following program, the
method setData( ) takes three parameter. The first
parameter is an Data object.
FINAL KEYWORDS
● In Java, the final keyword is used to denote CONSTANTS. It
can be used with variables, methods, and classes.
● Once any entity (variable, method or class) is declared final,
it can be assigned only once. That is,
● the final variable cannot be reinitialized with another value
● the final method cannot be overridden
● the final class cannot be extended
1. Java final Variable

● In Java, we cannot change the value of a final variable. For


example,
class Main
{
public static void main(String[]args)
{
final int AGE = 32;
AGE = 45; // try to change the final variable
[Link]("Age: " + AGE);
}}
● In the above program, we have created a final variable
named age. And we have tried to change the value of the
final variable.
● When we run the program, we will get a compilation error
with the following message.
● cannot assign a value to final variable AGE AGE = 45; ^
2. Java final Method

● Before learn about final


methods and final
classes, one should
know about the Java
Inheritance.
● In Java,
the final method cannot
be overridden by the
child class. For
example,
● In the above example, we have created a final method
named display() inside the FinalDemo class. Here,
the Main class inherits the FinalDemo class.
● We have tried to override the final method in the Main class.
When we run the program, we will get a compilation error
with the following message.
3. Java final Class

● In Java, the
final class
cannot be
inherited by
another class.
For example,
● In the above example, we have created a final class
named FinalClass. Here, we have tried to inherit the final
class by the Main class.
● When we run the program, we will get a compilation error
with the following message.
● cannot inherit from final FinalClass
● class Main extends FinalClass { ^
Built-in java class methods

● 1) What is Method?
● > A Java method is a set of statements that are grouped together to
perform an operation.
● > Methods are also known as Functions
● > In Structured programming (ex: C Language) we use Functions (Built in
and User defined)
● > In Object Oriented Programming we use Methods (Built in and User
defined)
● 2) When we choose Methods?
● Whenever we want to perform any operation multiple times then choose
methods.
Built in Methods in Java

● Basically we have 2 types of Methods


● 1) Built in Methods
● 2) User defined Methods
Categories of Built in Methods
● i) String Methods
● ii) Number Methods
● iii) Character Methods
● iv) Array Methods etc…
Java Number Methods

● 1) compareTo() Method (Number, 3-way comparison)


● public static void main (String [] args){
int x = 5; //An object of type Integer contains a single
field whose type is int.
Integer a =x; // Integer class wraps a value of the
primitive type int in an object
[Link]([Link](5));//0
[Link]([Link](6));//-1
[Link]([Link](4));//1
}
2) equals() Method (Number, 2-way comparison)

public static void main (String [] args){


int x = 5;
Integer a =x;
[Link]([Link](5));//true
[Link]([Link](6));//false
[Link]([Link](4));//false
}
——————————–
3) abs() -Returns absolute value

public static void main (String [] args){


double a =10.234;
double b =-10.784;
[Link]([Link](a));//10.234
[Link]([Link](b));//10.784
}
4) round() -It rounds the value to nearest integer

public static void main (String [] args){


double a =10.234;
double b =-10.784;
double c =10.51;
[Link]([Link](a));//10
[Link]([Link](b));//-11
[Link]([Link](c));//11
}
———————————–
5) min() – Returns minimum value between two numbers

public static void main (String [] args){


int a=10, b=20;
double c =10.234, d =10.345;
[Link]([Link](a, b));//10
[Link]([Link](c, d));//10.234
[Link]([Link](7, 9));//7
[Link]([Link](1.23, 1.234));//1.23
}
6) max()-Returns maximum value between two numbers
public static void main (String [] args){
int a=10, b=20;
double c =10.234, d =10.345;
[Link]([Link](a, b));//20
[Link]([Link](c, d));//10.345
[Link]([Link](7, 9));//9
[Link]([Link](1.23, 1.234));//1.234
}
————————————-
7) random() – Generates a random number
public static void main (String [] args)
{
[Link]([Link]());//
}
Java Character Methods

● 1) isLetter() – Checks weather the value is Alphabetic or not?


public static void main (String [] args)
{
char a =’A’; //The Character class wraps a value of primitive data type
char is an object
char b =’1′;
[Link]([Link](a)); //true
Method syntax:
[Link]([Link](b)); //false
[Link]()
[Link]([Link](‘Z’)); //true [Link]
[Link]([Link](‘1’)); //false Class/[Link]
[Link]([Link](‘*’)); //false
}
3) isUpperCase() – Checks weather the value is Upper
2) isDigit() -Checks weather the value is Number or
case or not?
not?
4) isLowerCase()-Checks weather the value is Lower
public static void main (String [] args){
//The Character class wraps a value of primitive data type char is an
case or not?
object Examples:
char a =’A’; public static void main (String [] args){
char b =’1′; //The Character class wraps a value of primitive data type
[Link]([Link](a));//false char is an object
[Link]([Link](b));//true char a =’A’;
[Link]([Link](‘Z’));//false char b =’z’;
[Link]([Link](‘1’));//true char c =’1′;
[Link]([Link](‘*’));//false [Link]([Link](a));//true
} [Link]([Link](b));//false
——————————- [Link]([Link](c));//false
[Link]([Link](a));//false
[Link]([Link](b));//true
[Link]([Link](c));//false
}
Java Array Methods

● 1) length -It returns length of the Array.


● public class Sample1 {
● public static void main (String [] args){
int [] array1 = {10, 20, 30, 40};
[Link]([Link]);//4
}
}
2) toString() -It prints an Array.
public static void main (String [] args){
String [] array1 = {“Selenium”, “UFT”, “LoadRunner”, “RFT”};
String str = [Link](array1);
[Link](str);
}
————————————-
3) contains() – Checks if the Array contains certain value or not?
public static void main (String [] args){
String [] array1 = {“Selenium”, “UFT”, “LoadRunner”, “RFT”};
boolean a = [Link](array1).contains(“UFT”);
boolean b = [Link](array1).contains(“Java”);
[Link](a);//true
[Link](b);//false
}
Strings

● Strings, which are widely used in Java programming, are a


sequence of characters. In Java programming language,
strings behave as objects and variables as well.
● The Java platform provides the String class to create and
manipulate strings.
● In Java, String is a secondary Data Type, it is used to store
the String values
● The most direct way to create a string is to write:
String greeting = "Hello world!";
Syntax:
1. String str;
2. String str= “str_variable”;
3. String str=new String();
4. String str=new String(“value”);
5. String str=new String(new char[]);
Creating Strings

● In this case, "Hello world!" is a string literal—a series of


characters in your code that is enclosed in double quotes.
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 thirteen constructors that allow you to provide the initial
value of the string using different sources, such as an array
of characters:
Example
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray); // String object
creation
[Link](helloString);
● The last line of this code snippet displays hello.
● Note: The String class is immutable, so that once it is created
a String object cannot be changed. The String class has a
number of methods, some of which will be discussed below,
that appear to modify strings. Since strings are immutable,
what these methods really do is create and return a new
string that contains the result of the operation.
String Length

● 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.
After the following two lines of code have been
executed, len equals 17:
String palindrome = "Dot saw I was Tod";
int len = [Link]();
A palindrome is a word or sentence that is symmetric—it is spelled the same forward and
backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a
palindrome string. It invokes the String method charAt(i), which returns the i th character in the
string, counting from 0.

public class StringDemo { public static void main(String[] args)


{ String palindrome = "Dot saw I was Tod";
int len = [Link]();
char[] tempCharArray = new char[len];
char[] charArray = new char[len]; // put original string in an array of chars
for (int i = 0; i< len; i++)
{
tempCharArray[i] = [Link](i);
} // reverse array of chars
for (int j = 0; j < len; j++)
{
charArray[j] = tempCharArray[len - 1 - j];
}
String reversePalindrome = new String(charArray);
[Link](reversePalindrome);
}
}
● Java String class provides a lot of methods
to perform operations on strings such as
compare(), concat(), equals(), split(),
length(), replace(), compareTo(), intern(),
substring() etc.
Java String charAt()

● The java string charAt() method returns a char value at the given index
number.
● The index number starts from 0 and goes to n-1, where n is length of the string. It
returns StringIndexOutOfBoundsException if given index number is greater
than or equal to this string length or a negative number.
● Syntax- public char charAt(int index)
public class CharAtExample {
public static void main(String args[]){
String name="javaprogramming";
char ch=[Link](4); //returns the char value at the 4th index
[Link](ch);
}}
Java String compareTo()
● The java string compareTo() method compares the given
string with current string lexicographically. It returns positive
number, negative number or 0.
● It compares strings on the basis of Unicode value of each
character in the strings.
● if s1 > s2, it returns positive number
● if s1 < s2, it returns negative number
● if s1 == s2, it returns 0
Syntax
● public int compareTo(String anotherString)
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
[Link]([Link](s2)); //0 because both are equal
[Link]([Link](s3)); //-5 because "h" is 5 times lower than "m"
[Link]([Link](s4)); //-1 because "l" is 1 times lower than "m"
[Link]([Link](s5)); //2 because "h" is 2 times greater than "f"
}}
Note:- If you compare string with blank or empty string, it returns length of the string. If
second string is empty, result would be positive. If first string is empty, result would be
negative.
Java String concat
The java string concat() method combines specified string at the end of this string. It
returns combined string. It is like appending another string.
Syntax:-
public String concat(String anotherString)

Example:-
public class ConcatExample
{
public static void main(String args[]){
String s1="java string";
[Link]("is immutable");
[Link](s1);
s1=[Link](" is immutable so assign it explicitly");
[Link](s1);
}}
Java String contains()
The java string contains() method searches the sequence of characters in this string. It
returns true if sequence of char values are found in this string otherwise returns false.
Syntax:-
public boolean contains(CharSequence sequence)

Example:-
class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
[Link]([Link]("do you know"));
[Link]([Link]("about"));
[Link]([Link]("hello"));
}}
Java String endsWith()
The java string endsWith() method checks if this string ends with given suffix. It returns true if this
string ends with given suffix else returns false.

Syntax:-
public boolean endsWith(String suffix)

Example:-
public class EndsWithExample{
public static void main(String args[]){
String s1=“Patna Women’s College";
[Link]([Link](“e"));
[Link]([Link](“College"));
}}
Extending classes

Inheritance
Inheritance in Java
● Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object
Oriented programming system).
● The idea behind inheritance in Java is that we can
create new classes that are built upon existing
classes. When we inherit from an existing class, we
can reuse methods and fields of the parent class.
Moreover, we can add new methods and fields in our
current class also.
Why use inheritance in java

●For Method Overriding (so runtime


polymorphism can be achieved).
●For Code Reusability.
TERMS USED IN INHERITANCE

● Class: A class is a group of objects which have common properties. It


is a template or blueprint from which objects are created.
● Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
● Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
● Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class
when you create a new class. You can use the same fields and methods
already defined in the previous class.
THE SYNTAX OF JAVA INHERITANCE

class Subclass-name extends Superclass-name


{
//methods and fields
}

● The extends keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is to
increase the functionality.
● In the terminology of Java, a class which is inherited is called a
parent or superclass, and the new class is called child or subclass.
Java Inheritance
Example

As displayed in the given figure, Programmer is the


subclass and Employee is the superclass. The
relationship between the two classes is Programmer
IS-A Employee. It means that Programmer is a type
of Employee.
Programming
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Inheritance Type
● On the basis of class, there can be three types of inheritance
in java: single, multilevel and hierarchical.
● In java programming, multiple and hybrid inheritance is
supported through interface only. We will learn about
interfaces later.
● We will learn now:-
1. Single Inheritance
2. Multilevel Inheritance
Single Inheritance
When a class inherits another class, it is known as a single
inheritance. In the example given below, Dog class inherits the
Animal class, so there is the single inheritance.
class Animal{
void eat()
{
[Link]("eating...");}
}
class Dog extends Animal
{
void bark()
{[Link]("barking...");}
}
class TestInheritance
{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Multilevel Inheritance
● When there is a chain of inheritance, it is known
as multilevel inheritance. A class inherits a class which
already inherits some other class
● In the example given below, BabyDog class inherits the Dog
class which again inherits the Animal class, so there is a
multilevel inheritance.
Example
class Animal
{
void eat(){[Link]("eating...");}
}
class Dog extends Animal
{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog
{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Method Overriding
● In a class hierarchy, when a method in a subclass has the same
name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a
subclass, it will always refer to the version of that method
defined by the subclass. The version of the method defined by
the superclass will be hidden.
● Method overriding is one of the way by which java achieve Run
Time Polymorphism.
The main advantage of method
overriding is that the class can give its
own specific implementation to a
inherited method without even
modifying the parent class code.
class Human{ //Overridden method
public void eat()
{
[Link]("Human is eating");
}
public void move()
{
[Link](“Human are moving”);
}
}

class Boy extends Human{ //Overriding method


public void eat()
{
[Link]("Boy is eating");
}
public static void main( String args[])
{
Boy obj = new Boy(); //This will call the child class version of eat()
[Link]();
[Link]();
}
}
Interfaces
Interface looks like a class but it is not a class. An interface can
have methods and variables just like the class but:-
● the methods declared in interface are by default abstract
(only method signature, no body).
● Also, the variables declared in an interface are public, static
& final by default.
● An interface is implicitly abstract. You do not need to use
the abstract keyword while declaring an interface.
What is the use of interface in Java?

● As mentioned above they are used for full abstraction. Since


methods in interfaces do not have body, they have to be
implemented by the class before you can access them.
● The class that implements interface must implement all the
methods of that interface.
● Java programming language does not allow you to extend
more than one class. However we can implement more than
one interfaces in your class.
An interface is similar to a class in the following ways −

● An interface can contain any number of methods.


● An interface is written in a file with a .java extension, with
the name of the interface matching the name of the file.
● The byte code of an interface appears in a .class file.
● Interfaces appear in packages, and their corresponding
bytecode file must be in a directory structure that matches
the package name.
However, an interface is different from a class in several
ways, including −

● You cannot instantiate an interface.


● An interface does not contain any constructors.
● All of the methods in an interface are abstract.
● An interface cannot contain instance fields. The only fields
that can appear in an interface must be declared both static
and final.
● An interface is not extended by a class; it is implemented by
a class.
● An interface can extend multiple interfaces.
Syntax
interface MyInterface
{
/* All the methods are public abstract by default *
As you see they have no body */
public void method1();
public void method2();
}
interface MyInterface
{
public void method1();
public void method2();
}

class Demo implements MyInterface


{ /* This class must have to implement both the abstract methods * else you will get compilation error */
public void method1()
{
[Link]("implementation of method1");
}
public void method2()
{
[Link]("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
Filename [Link]
interface Animal
{
public void eat();
public void travel();
}
Filename [Link]
public class MammalInt implements Animal {
public void eat()
{ [Link]("Mammal eats"); }
public void travel()
{ [Link]("Mammal travels"); }
public int noOfLegs()
{ return 0; }
public static void main(String args[]) {
MammalInt m = new MammalInt();
[Link]();
[Link](); } }
Java Package
● A java package is a group of similar types of classes,
interfaces and sub-packages.
● Package in java can be categorized in two form, built-in
package and user-defined package.
● There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
Advantages of Java Package

● 1) Java package is used to


categorize the classes and
interfaces so that they can be
easily maintained.
● 2) Java package provides access
protection.
● 3) Java package removes naming
collision.
Simple example of java package
package mypack; How to compile java package:
public class Simple{ javac -d directory javafilename
public static void main(String a
rgs[]) javac -d . [Link]

{ The -d switch specifies the destination where to put


[Link]("Welcome to p the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of
ackage"); windows) etc. If you want to keep the package within
} the same directory, you can use . (dot).

} To Compile: javac -d . [Link]


To Run: java [Link]
How to access package from another package?

There are three ways to access the package from outside the
package.
● import package.*;
● import [Link];
● fully qualified name.
Accessing one package from another

//save by [Link] //save by [Link]


package mypack1;
package pack; import pack.*;
public class A{
class B{
public void msg() public static void main(String args[]){
A obj = new A();
[Link]();
}
{[Link]("Hello");} }
}

Compile by javac –d . [Link]


Compile by javac –d . [Link]
Run By java mypack1.B
JAVA SWING
● Java Swing tutorial is a part of Java Foundation Classes (JFC) that
is used to create window-based applications. It is built on the top of
AWT (Abstract Windowing Toolkit) API and entirely written in java.
● Unlike AWT, Java Swing provides platform-independent and
lightweight components.
● The [Link] package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
● Provides a set of "lightweight" (all-Java language) components that,
to the maximum degree possible, work the same on all platforms.
Hierarchy of Java Swing classes
Commonly used Methods of Component class
Java Swing Examples

There are two ways to create a frame:


● By creating the object of Frame class (association)
● By extending Frame class (inheritance)
Creating object of Frame Class
Simple example of Swing by inheritance
Swing JComponents
● The class JComponent is the base class for all Swing
components except top-level containers. To use a
component that inherits from JComponent, you must place
the component in a containment hierarchy whose root is a
top-level SWING container.
● [Link]
Java JTextField

● The object of a JTextField class is a text component that allows


the editing of a single line text. It inherits JTextComponent class.

JTextField class declaration


● public class JTextField extends JTextComponent implements SwingConstant
s
import [Link].*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to PWC");
[Link](50,100, 200,30);
t2=new JTextField(“This is Java");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
}
}
import [Link].*;
import [Link].*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2; public void actionPerformed(ActionEvent e) {
TextFieldExample(){ String s1=[Link]();
JFrame f= new JFrame(); String s2=[Link]();
tf1=new JTextField(); int a=[Link](s1);
[Link](50,50,150,20); int b=[Link](s2);
tf2=new JTextField();
[Link](50,100,150,20);
int c=0;
tf3=new JTextField(); if([Link]()==b1){
[Link](50,150,150,20); c=a+b;
[Link](false); }else if([Link]()==b2){
b1=new JButton("+"); c=a-b;
[Link](50,200,50,50); }
b2=new JButton("-"); String result=[Link](c);
[Link](120,200,50,50);
[Link](result);
[Link](this);
[Link](this);
}
[Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2); public static void main(String[] args) {
[Link](300,300); new TextFieldExample();
[Link](null); }}
[Link](true);
}
Java JLabel

● The object of JLabel class is a component for placing text in a


container. It is used to display a single line of read only text.
The text can be changed by an application but a user cannot
edit it directly. It inherits JComponent class.
JLabel class declaration
● public class JLabel extends JComponent implements Swing
Constants, Accessible
import [Link].*;
class JLabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
l2=new JLabel("Second Label.");
[Link](50,100, 100,30);
[Link](l1); [Link](l2);
[Link](300,300);
[Link](null);
[Link](true);
}
}
JPasswordField
● The object of a JPasswordField class is a text component
specialized for password entry. It allows the editing of a
single line of text. It inherits JTextField class.
● public class JPasswordField extends JTextField
import [Link].*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
[Link](20,100, 80,30);
[Link](100,100,100,30);
[Link](value); [Link](l1);
[Link](300,300);
[Link](null);
[Link](true);
}
}
import [Link].*;
import [Link].*; [Link](value); [Link](l1); [Link](label); [Link](l2); [Link](b);
public class PasswordFieldExample1 { [Link](text);
[Link](300,300);
public static void main(String[] args) {
[Link](null);
JFrame f=new JFrame("Password Field Example");
[Link](true);
[Link](new ActionListener() {
final JLabel label = new JLabel(); public void actionPerformed(ActionEvent e) {
[Link](20,150, 200,50);
final JPasswordField value = new JPasswordField(); String data = "Username " + [Link]();
data += ", Password: "
[Link](100,75,100,30); + new String([Link]());
[Link](data);
JLabel l1=new JLabel("Username:");
}
[Link](20,20, 80,30); });
JLabel l2=new JLabel("Password:"); }
[Link](20,75, 80,30); }
JButton b = new JButton("Login");
[Link](100,120, 80,30);
final JTextField text = new JTextField();
[Link](100,20, 100,30);
Event and Listener (Java Event Handling)

● Changing the state of an


object is known as an event.
For example, click on button,
dragging mouse etc. The
[Link] package
provides many event classes
and Listener interfaces for
event handling.
[Link] class provides many methods for
graphics programming.
● Commonly used methods of Graphics class:
● public abstract void drawString(String str, int x, int y): is used to draw
the specified string.
● public void drawRect(int x, int y, int width, int height): draws a rectangle
with the specified width and height.
● public abstract void fillRect(int x, int y, int width, int height): is used to
fill rectangle with the default color and specified width and height.
● public abstract void drawOval(int x, int y, int width, int height): is used
to draw oval with the specified width and height.
● public abstract void fillOval(int x, int y, int width, int height): is used to
fill oval with the default color and specified width and height.
● public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw line between the points(x1, y1) and (x2, y2).
● public abstract boolean drawImage(Image img, int x, int
y, ImageObserver observer): is used draw the specified
image.
● public abstract void drawArc(int x, int y, int width, int
height, int startAngle, int arcAngle): is used draw a circular
or elliptical arc.
● public abstract void fillArc(int x, int y, int width, int
height, int startAngle, int arcAngle): is used to fill a circular
or elliptical arc.
● public abstract void setColor(Color c): is used to set the
graphics current color to the specified color.
● public abstract void setFont(Font font): is used to set the
graphics current font to the specified font.
For registering the component with the Listener, many classes provide the registration methods. For example:
● Button
○ public void addActionListener(ActionListener a){}
● MenuItem
○ public void addActionListener(ActionListener a){}
● TextField
○ public void addActionListener(ActionListener a){}
○ public void addTextListener(TextListener a){}
● TextArea
○ public void addTextListener(TextListener a){}
● Checkbox
○ public void addItemListener(ItemListener a){}
● Choice
○ public void addItemListener(ItemListener a){}
● List
○ public void addActionListener(ActionListener a){}
○ public void addItemListener(ItemListener a){}
Java AWT Button Example with ActionListener
import [Link].*;
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
final TextField tf=new TextField();
[Link](50,50, 150,20);
Button b=new Button("Click Here");
[Link](50,100,60,30);
[Link](new ActionListener(){
public void actionPerformed(ActionEvent e){
[Link]("Welcome to PWC.");
}
});
[Link](b);[Link](tf);
[Link](400,400);
[Link](null);
[Link](true);
}
Java AWT TextArea Example with ActionListener
import [Link].*;
import [Link].*; public void actionPerformed(ActionEvent e)
public class TextAreaExample extends Frame implements ActionListener {
{ String text=[Link]();
Label l1,l2; String words[]=[Link]("\\s");
TextArea area; [Link]("Words: "+[Link]);
Button b; [Link]("Characters: "+[Link]());
TextAreaExample(){ }
l1=new Label();
public static void main(String[] args) {
[Link](50,50,100,30);
new TextAreaExample();
l2=new Label();
}
[Link](160,50,100,30);
}
area=new TextArea();
[Link](20,100,300,300);
b=new Button("Count Words");
[Link](100,400,100,30);
[Link](this);
add(l1);add(l2);add(area);add(b);
setSize(400,450);
setLayout(null);
setVisible(true);
}
import [Link].*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
[Link](100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
[Link](100,150, 50,50);
[Link](checkbox1);
[Link](checkbox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{

You might also like