0% found this document useful (0 votes)
3 views15 pages

Java Notes Only 8

The document provides an overview of classes, objects, and methods in Java, explaining the definitions, rules for naming, and how to create and use them. It covers concepts such as constructors, method overloading, static members, and inheritance, detailing their syntax and usage with examples. Additionally, it highlights the differences between constructors and methods, as well as static and non-static variables.

Uploaded by

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

Java Notes Only 8

The document provides an overview of classes, objects, and methods in Java, explaining the definitions, rules for naming, and how to create and use them. It covers concepts such as constructors, method overloading, static members, and inheritance, detailing their syntax and usage with examples. Additionally, it highlights the differences between constructors and methods, as well as static and non-static variables.

Uploaded by

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

8.

Classes, Objects and Methods


Classes provide a convenient method for packing together a group of logically related data
items and functions that work on them.
In java, the data items are called Fields and the functions are called Methods.
Definition of Class: A class defined as a blueprint or prototype from which objects are
created and it contains data and member functions. (OR)
A class is a user-defined data type with a template that serves to define its properties
Defining a class:
The basic form of a class definition is:
class classname [extends superclassname]
{
[field declaration;]
[method declaration;]
}
classname and superclassname are any valid Java identifiers . The keyword extends indicates
that the properties of the superclassname class are extended to the classname class .This
concept is known as inheritance. Fields and methods are declared inside the body of a class
Once the class type has been defined, we can create “variables” of that type using
declarations that are similar to the basic type declarations.
In Java, these variables are termed as Instances of classes or objects.
Rules for naming classes:
1. A class name must not be a keyword in java
2. It can begin with a letter , an underscore or $ sign
3. The name must not contain space or period
4. They can be of any length
5. class names must begin with uppercase letter
6. if it is too long , the leading uppercase letter and each subsequent word with a leading
upper case letter Ex : HelloWorld , AreaOfTriangle etc
Creating Objects:
An object is an instance of class. Creating an object is also known as instantiating an
object .Objects in Java are created using the new operator. The new operator creates an object
of the specified class and returns a reference to that object.
Example:
Student stud; //declare the object
stud =new student (); // instantiate the object
The first statement declares a variable to hold the object reference and the second statement
assigns the object reference to the variable
Both statements can be combined in to one
Student stud=new Student ();
Here the method Student ( ) is a default constructor of the class. We can create any number of
objects of class.
Field Declarations:
Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instances variables. These Variables are created whenever an
object the class is instantiated.
Declaration of instance variables:
class Student
{
String name;
int rollno ;
float avg;

Page 1 of 15
}

Here class Student contains three instance variables ie , name of type String , rollno of type
int and avg of type float .
 Instance variables are also known as member variables (or data members) because
they are created whenever an object of a class is created .
 The variables are called instance variables because every time the class is
instantiated , a new copy of each of them is created
 The variables are accessed by using a dot operator ( . )
 The syntax is :
[Link]=value ;
Here objectname is name of the object , variablename is the name of the instance variable
inside the object which we want to access, value is the value assigned to the variable .
EX : Student std =new Student( ) ;//creating object for student class
[Link]=”priyanka”;//accessing variables
[Link]=12; // accessing variables
Method Declaration :
Methods are declared inside the body of the class immediately after the declaration of
instance variables .The general form of method declaration is
type methodname (parameter-list)
{
method-body ;
}
Method declarations have four basic parts:
 The name of the method ie, methodname
 The type of the value the method returns
 A list of parameters
 The body of the method
 The type specifies the type of the value the method would return .type may be a
simple data type such as int as well as any class type .it could be void if the method
does not return any value
 The methodname is a valid identifier
 The parameter list is always enclosed in parenthesis .This list contains variable
names and type of the variable .The variables in the list are separated by commas.
 The body describes the operations to be performed on the data
Example:
area(float l ,float b)
marks( )
 The instance methods are accessed by using the dot operator
 The syntax is :
[Link](parameter-list);
Here objectname is name of the object, .methodname is the name of the method , and the
parameter list separated by commas
Example:
Student std =new Student( ) ;
[Link]=”priyanka”;//accessing variables
[Link]=12; // accessing variables
[Link](“sasidhar”,1);// accessing methods
Conventions for naming methods:
Method name should start with lowercase letter. If method name is having more than
one word then the second word onwards first letter must begin with a uppercase
letter .Ex:calculateTotal ( ),displayItems( ) etc.,

Page 2 of 15
Example
class Student
{
String name;
int rollno ;
void getData(String n, int r)
{
name=n;
rollno=r;
}
}
Note: here in this example, method getData( ) does not return any value so return type is
void. Here we are passing two parameters to the method, n which is of String type and r of int
type which are then assigned to the instance variables name and rollno.
Instance variables and methods in classes are accessible by all the methods in the class but a
method cannot access the variables declared in other methods.
Example :
import [Link].*:
class Triangle
{
int breadth,height ;
void getData(int x,int y)
{
breadth=x;
height=y;
}
float triArea( )
{
float area=(0.5*breadth*height);
return(area);
}
}
class TriangleTest
{
public static void main(String args[])
{
float area1,area2;
Triangle tri1 =new Triangle( ) ;
Triangle tri2 =new Triangle( ) ;
[Link]=8;
[Link]=5;
area1=[Link]*[Link];
[Link](5,5);
area2=[Link]( );
[Link](“Area 1 Is “+area1);
[Link](“Area 2 Is “+area2);
}
}
Constructors:
Constructors are used to initialize the instance variables of an object at the time of its
creation
 A constructor is special function that is a member of the class and has the same
name as that of class.

Page 3 of 15
 An object’s constructor is called when the object is created.
 Constructors are used for initializing values to the data members (Instance
variables) of the class.
 constructors are implicitly called when an object is created
 Constructors can be overloaded i.e, A class can have any [Link] constructors with
variation in parameter-list
 if you have not defined any constructor , then java will automatically define a
constructor without any parameters and that constructor is known as default
constructor .The syntax of default constructor is
classname( )
{ }
Ex: Triangle( )
{ }
 Constructors do not return any value not even void .
 They are only used for initialization and not used for input /output operations .
Example:
import [Link].*:
class Triangle
{
int breadth,height ;
Triangle (int x, int y) //Defining constructor
{
breadth = x;
height = y;
}
float triArea( )
{
float area=(0.5*breadth*height);
return (area);
}
}
class TriangleTest
{
public static void main(String args[])
{
float area1;
Triangle tri1 =new Triangle( 5,4) ;
area1=[Link]( );
[Link](“Area1 Is “+area1);
}
}
What are the Differences between constructor and Method?
Constructor Method
It has the same name as the class itself It has its own name , because it is an ordinary
member function of a class
Constructor has no return type Method have return type (which may be void )
Constructor are invoked by the new operator Method is invoked using the dot operator.
Syntax : classname(parameter-list) Syntax: return-type methodname(parameter-list)
{ {
Body of the constructor; Body of method ;
} }
Method Overloading:
Page 4 of 15
Method Overloading or polymorphism is a process of defining two or more methods
having the same name with different argument or parameter list performing the same task.
Java allows method overloading as long as the each parameter list is unique for the same
method name
A method can be overloaded
 Based on type of parameters
 Based on number of parameters
 Based on the order of parameters
1. Overloading is not possible if there is only change in the return type of the method
2. Overloading is not possible when there is no change in the argument list , either in
terms of type of arguments or in terms of number of arguments and there is only
change in return type
3. When method is called in an object, Java (jvm )selects the appropriate version of the
methods depending on the method signature (method signature means parameters
count,data types and their order ).
Example:
class Biggest
{
int big(int x, int y )
{
return (x>y ? x : y);
}

int big(int x, int y ,int z)


{
return (x>y ? (x>z ? x : z) : ( y > z ? y :z );
}
double big(double x, double y )
{
return (x>y ? x : y);
}
}
class OverloadTest
{
public static void main(String args[ ] )
{
OverloadTest obj=new OverloadTest( );
[Link]([Link](10,20));
[Link]([Link](5 ,10,20));
[Link]([Link](5.65,,3.24));
}
}
Static Members:
Static Variable or class variable:
 A Static variable is one which is belonging to the entire class. There will be only
one memory location for a class variable for any no. of objects
 This variables are declared using the keyword static
Syntax: static type variable=value;
 Static variables are also called as class variables
 Java creates only one copy for a static variable which can be used even if the
class is never instantiated
 A class variable can be accessed by using the
Syntax:

Page 5 of 15
classname . staticvariablename ;
Note: Instance variables can be accessed only by using object reference ie
[Link]

Example: //[Link]
class StaticDemo
{
int a=10;
static int b=25;
}
class TestStatic
{
public static void main(String args[ ] )
{
[Link](TestStatic.b);
StaticDemo obj=new StaticDemo( );
[Link](obj.a);
}
}
Static Methods or Class Methods :
 Static methods are also called as Class Methods.
 Static method is a method that does not act upon the instance variables of a class
 Static method is declared by using the keyword ‘static’ and its syntax : static
return-type methodname( parameter-list)
 Static methods are called using the syntax
[Link]( );
 Java class library contain a large number of class methods
For example, the Math class of java library defines many static methods
ex: float a=[Link](25.0);
Note:
1. Static methods and static variables are accessed without using a particular object
2. static methods can only call other static methods
3. static methods can only access static data
4. They cannot refer to this or super in any way
What are the differences between static variables and non-static variables?
 When a variable of class is non-static then it is known as instance variable , on
the other hand if it is static then it is known as class variable
 Instance variables can be accessed only along with objects of its class where as
class variables can be accessed without any reference of the objects
 Each Instance of class will have its own copy of instance variable whereas all the
instances of a class will share same copy of a class variable.
 In Java by using the keyword static we can create global variables.

Nesting of methods:

A method of a class is called only by the object of that class using the dot operator. A
method can also be called by using only its name by another method of the same class this is
known as nesting of methods

Note: A method can call any number of methods. It is also possible for a called method to
call another method

Example: //[Link]

Page 6 of 15
class Nesting
{
int a,b ;
Nesting (int x, int y) // constructor
{
a=x;
b=y;
}
int largest( )
{
if(a>b)
return (a);
else
return(b);
}
void display( )
{
int large=largest(); // calling a method
[Link](“The largest value is “ +large);
}
}
class NestingDemo
{
public static void main (String args[ ])
{
Nesting obj=new Nesting( 90,45);
[Link]( );
}
}
Inheritance: Extending a class
 Inheritance :The mechanism of deriving a new class from an existing class (old
class ) is called as Inheritance .
 The existing class is known as base class or super class or parent class
 The new class is known as sub class or derived class or child class
 The inheritance allows subclasses to inherit all the variables and methods of their
parent classes
Types of Inheritance:
Inheritance can be classified into
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
Single Inheritance:
Deriving a class from only one super class is known as single inheritance.

Super class

Subclass

Multiple Inheritances:

Page 7 of 15
Deriving a class from several (two or more) super classes is called as Multiple Inheritance.

A B

Multiple Inheritances is not supported in Java but it can be accomplished using Interfaces.
Hierarchical Inheritance :
Deriving several classes from single super class is called as Hierarchical
Inheritance

B C D

Multilevel Inheritance:
Derivation of a class from another derived class is known as Multilevel Inheritance.

Defining Subclass:
A subclass is defined as follows:
class subclassname extends superclassname
{
Variables declaration ;
Methods declaration;
}

The keyword extends signifies that the properties of the superclassname are extended to the
subclassname .The subclass contains its own variables and methods as well those of the
supercalss

Example for single level Inheritance


class A
{

Page 8 of 15
int x,y;
void setxy(int a , int b)
{
x=a;
y=b;
}
void showxy( )
{
[Link](“x=” +x +” “ +”y= “ +y);
}
} //A class end
class B extends A
{
int z;
void setz (int c)
{
z=c;
}
void showz( )
{
[Link](“z=” +z );
}
void sum( )
{
[Link](“x+y+z=” +(x+y+z));
} //B class end
class Inheritance
{
public static void main(String args[ ])
{
A a1=new A( );
B b1=new B( );
[Link](10,20);
[Link]( );
[Link](100,200);
[Link](300);
[Link]( );
[Link]( );
[Link]();
}
}
Super Keyword:
A subclass can refer its immediate super class by using the keyword super .The super
keyword is used in following conditions
 Calling a super class constructor
 Calling a super class method
 Accessing a super class variable

Calling a super class constructor:


 When a subclass object is created it will have to initialize the instance variables of the
super class and sub class.
 The instance variables of the super class can be initialized by calling the super class
constructor from sub class constructor

Page 9 of 15
 The keyword ‘super’ can be used in the sub class constructor to call the super class
constructor by passing the arguments to initialize super class instance variables.
 When super keyword is used in the subclass constructor it must be the first statement
used in the subclass constructor.
Syntax for calling super class constructor:
super (parameter-list);
Example :
class Test 1
{
int i , j;
Test1( int x , int y)
{
i=x;
j=y;
}
void showij( )
{
[Link](“i= “ + i +” “ +”j= “ +j);
}
}
class Test2 extends Test1
{
int k ;
Test2(int x, int y , int z)
{
super(x, y);
k=z;
}
void showk( )
{
[Link](“k= “ +k);
}
}
class TestSuper
{
public static void main(String args[ ])
{
Test2 obj= new Test2(10,20,30 );
[Link]( );
[Link]( );
}
}
Calling a super class method from a subclass method :
A super class method can be called from a sub class method using the syntax:
[Link](parameter-list);
Example :
class Test 1
{
int i , j;
Test( int x , int y)
{
i=x;
j=y;

Page 10 of 15
}
void showij( )
{
[Link](“i= “ + i +” “ +”j= “ +j);
}
}
class Test2 extends Test1
{
int k ;
Test2(int x, int y , int z)
{
super(x, y);
k=z;
}
void showk( )
{
[Link]();
[Link](“k= “ +k);
}
}
class TestSuper
{
public static void main(String args[ ])
{
Test2 obj= new Test2(10,20,30 );
[Link]( );
}
}
Accessing a super class variable:
When a subclass and super class have instance variables with the same names then we can
access super class instance variable in the sub class using the syntax:
[Link]=value;
Example:
class A
{
int i;
}
class B extends A
{
int i ;
B(int x,int y)
{
super.i=x;
i=y;
}
void show( )
{
[Link](super.i);
[Link](i);
}
}

class Test

Page 11 of 15
{
public static void main(String args[ ])
{
B obj=new B(20,30 );
[Link]( );
}
}
Subclass Constructor:
The subclass constructor is used to construct the instance variables of both the
subclass and superclass. The subclass constructor uses the keyword super to invoke the
constructor method of the superclass. The super keyword can be used in the following
conditions:
 super may only be used within the subclass constructor method
 The call to superclass constructor must appear as the first statement within the
subclass constructor.
 The parameters in the super call must match the order and type of the instance
variables declared in the superclass.
Multilevel Inheritance:
The class A serves as a base class for derived class B which in turn serves as a base class
for the derived class C .The chain ABC is known as Inheritance
Instance variables :name,age,sex
Person methods:getData(),showData()

Student Instance variables:rollno,branch


Methods:getData(),showData()

Exam Instance variables:m1,m2


Methods:getData(),showData()

Overriding Methods or 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 in the superclass will be
hidden. If we wish to access the superclass version of an overridden method, you can do so
by using ‘super’.
Example:
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display ( )
{
[Link](“super x=”+x);
}
}

Page 12 of 15
class Sub extends Super
{
int y ;
sub(int x , int y)
{
super(x);
this.y=y;
}
void display( )
{
[Link](“super x=”+x);
[Link](“sub y =”+y);
}
}
class OverrideTest
{
public static void main(String args[ ] )
{
Sub s1=new Sub (100,200);
[Link]( );
}
}
Note: method display() defined in the subclass is invoked
this Keyword:
this keyword can be used inside any method to refer the current object .that
means this keyword is always reference to object on which the method was invoked .
Final Variables and Methods:
Final variables:
Attributes of a class can be declared as final indicating that the value of that particular
variable cannot be changed. The value of final variable must be provided at the time of
declaration. Local variables can’t be declared as final variables. Variables are declared final
by using the keyword ‘final ‘
Syntax: final type variablename=value ;
Final Methods :
Methods can be declared as final indicating that they cannot be overridden by subclasses. i.e,
if we wish to prevent the subclasses from overriding the methods then we can declare them as
final using the keyword final
Syntax:
final returntype methodname( parameter-list)
{
}
Final Classes:
A class that cannot be subclassed is called a ‘final class’. Classes can be declared as final to
ensure security .The class can be declared as final, if instances or subclasses are not to be
created. Java’s class hierarchy has many final classes, some of them are String, Boolean,
Math, Character, etc.
Syntax:
final class ClassName { ………….}
final class ClassName extends SomeClass { ……………}
Note: Any attempt to inherit these classes will cause an error and the compiler will not allow
it.
Finalizer Method:

Page 13 of 15
Finalizers are a method that is called immediately before a class is garbage-
collected. The garbage collection is important feature of Java.
It automatically frees up the memory resources used by java objects but objects may hold
non-object resources such as file descriptors or window system fonts . The garbage collector
cannot free these resources. In order to free these resources we must use a finalizer method
 Finalize() is used to release the system resources other than memory(such as file
handles& network connections
 Finalize() is called only once for an Object. If any exception is thrown in the finalize() the
object is still eligible for garbage collection.
 Finalize() should be called explicitly.
 Finalize( ) may only be invoked once by the Garbage Collector when the Object is
unreachable.
 The signature finalize( ) :
Protected void finalize() throws Throwable { }
Abstract Methods and Classes:
Abstract Method:
An abstract method is one which is defined in super class but not implemented. An
abstract method must be implemented by subclasses .that means an abstract method must be
overridden.
An abstract method doesn’t contain any body.
Syntax: abstract returntype functionname( );
Abstract Classes:
Any class that contains one or more abstract methods is known as Abstract class.
To declare a class as an abstract class use the keyword abstract infront of the class definition.
Syntax: abstract class ClassName { ………..}
Example:
abstract class Shape
{
…………..
…………….
abstract void draw( );
……………..
……………..
}
1. An abstract class can’t be instantiated that is we can’t create objects of a class
i.e., Shape s=new Shape() is illegal because Shape is an abstract class .
2. we can’t declare a constructor or a static methods
3. Any subclass of an abstract class must implement all the methods in the superclass
otherwise it has to be declared as abstract.
4. Even though we can’t create objects to abstract class but we can create object references
5. Even if a single method is declared as abstract in a Class, the class itself can be declared
as abstract.
6. Abstract class have at least one abstract method and others may be concrete.
7. In abstract Class the keyword abstract must be used for method.
8. Abstract classes have sub classes.
9. Combination of modifiers Final and Abstract is illegal in java.
Visibility controls :
The access to classes, methods, constructors, fields are regulated using access modifiers .i.e.,
a class can control what information or data can be accessible by other classes
Java provides a number of access modifiers to help you set a level of access you want for
classes as well as the fields ,methods, constructors in our classes .
Access modifiers are also called as visibility modifiers

Page 14 of 15
Access modifiers are
1. public :- Any variable or method is visible to the entire class in which it is
defined .This is possible by simply declaring the variable or method as “ public “
ex: public int number ;
public void display( );
A variable or method declared as “public” has the widest possible visibility and
accessible everywhere.
2. private :-They are accessible only within their own class .They can’t be inherited by
subclasses and therefore not accessible in subclasses .The method declared as
“private“ behaves like a method declared as final .It prevents the method from being
subclassed.
3. protected:-The “protected” modifier makes the fields visible not only to all classes
and subclasses in the same package but also to subclasses in other packages .Non-
subclasses in other packages cannot access the ” protected” member
4. friendly :-When no access modifier is specified , the member defaults to a limited
version of public accessibility known as “friendly” level of access . The difference
between the “public” access and the “friendly” access is that the public modifier
makes the fields visible in all classes , regardless of their packages while the friendly
access makes fields visible only in the same package ,but not in other packages.
5. private protected :- A field can be declared with two keywords private and
protected together like :
private protected int code;
This gives a visibility level in between the “protected” access and “private” access
This modifier makes the fields visible in all subclasses regardless of what package
they are in .But these fields are not accessible by other classes in the same package
Rules of Thumb :-Given below are some simple rules for applying appropriate access
modifiers
1. use public if the field is to be visible everywhere.
2. use protected if the field is to be visible everywhere in the current package and
also subclasses in other packages.
3. use default if the field is to be visible everywhere in the current package only
4. use private protected if the field is to be visible only in subclasses , regardless of
packages .
5. use private if the field is not to be visible anywhere except in its own class.

*****

Page 15 of 15

You might also like