Create A Class: Unit Ii Classes, Objects and Methods
Create A Class: Unit Ii Classes, Objects and Methods
Create A Class: Unit Ii Classes, Objects and Methods
Object - An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.
Create a Class
To create a class, use the keyword class:
class classname
field declaration;
method declaration;
MyClass.java
Create a class named "MyClass" with a variable x:
class MyClass {
int x = 5;
Field Decaration
1 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Data fields inside the class declaration
Named as Instance variable because they are created whenever an object of the
class is instantiated
These variables are only declared and therefore no storage space has been
created in the memory
Also called member variable
class Rectangle {
Method Declaration
Declared inside the body of the classs immediately after the declaration of instance variable
Syntax
method body;
2 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
length=x;
width=y; body od method
}
}
Creating Objects [Instantiating Object]
The new operator creates an object of the specified class and returns a reference to that
object.
The method Rectangle() is the default constructor of the class. We can create any number of
objects of Rectangle.
Action Statement Result
Rectangle
object
Any changes to the variables of one object have no effect on the variables of another
It is also possible to create two or more references to the same object as in the following
figure.
3 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
R1
Rectangle
Object
R2
objectname.variablename=value;
objectname.methodname(parameter-list);
There are 3 ways to initialize object in Java. Initializing an object means storing data into
the object.
1. By reference variable
2. By method
3. By constructor
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
4 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
s1.id=101; // assigning value to instance variable id
s1.name="Architha"; // assigning value to instance variable name
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Output:
101 Architha
We can also create multiple objects and store information in it through reference
variable.
File: TestStudent3.java
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student(); // first object instantiated
Student s2=new Student(); // second object instantiated
//Initializing objects
s1.id=101; // assigning value to instance variable id trough s1
s1.name="Sonoo"; // assigning value to instance variable name trough s1
s2.id=102; // assigning value to instance variable id trough s2
s2.name="Amit"; // assigning value to instance variable name trough s2
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 Sonoo
102 Amit
File: TestStudent4.java
5 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and
s2 both are reference variables that refer to the objects allocated in memory.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.
The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.
<class_name>(){}
class MyClass {
7 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
// Create a class constructor for the MyClass class
MyClass() {
// Output 0
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
8 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
9 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
111 Karan 0
222 Aryan 25
A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not be
same as the class name.
When we call a method in an object, Java matches up the method name first and
then number and types of parameters to decide which one of the definitions to
execute.
In java, method overloading is not possible by changing the return type of the
method only because of ambiguity.
By method overloading, You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only.
10 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
// Overloaded sum(). This sum takes three int parameters
int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double parameters
double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output :
30
60
31.0
Eg:
Static members are associated with class itself rather than individual
objects so static variables and static methods are referred ad class
variables and class methods.
11 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
1) Java static variable [Class Variable]
If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name; //instance variable
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
12 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Java static method [Class Method]
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
classname.classmethod();
o A static method can access static data member and can change the value of it.
13 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling static method without creating object
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Rules
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
Nesting of Methods
A method can be called by using only its name by another method of the same class.
This is known as nesting of methods.
import java.util.Scanner;
public class Nesting_Methods
{
int perimeter(int l, int b)
{
int pr = 12 * (l + b);
14 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
return pr;
}
int area(int l, int b)
{
int pr = perimeter(l, b);
System.out.println("Perimeter:"+pr);
int ar = 6 * l * b;
return ar;
}
int volume(int l, int b, int h)
{
int ar = area(l, b);
System.out.println("Area:"+ar);
int vol ;
vol = l * b * h;
return vol;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter length of cuboid:");
int l = s.nextInt();
System.out.print("Enter breadth of cuboid:");
int b = s.nextInt();
System.out.print("Enter height of cuboid:");
int h = s.nextInt();
Nesting_Methods obj = new Nesting_Methods();
int vol = obj.volume(l, b, h);
System.out.println("Volume:"+vol);
}
}
// of return keyword
class A {
{
double sum = 0;
sum = (a + b) / 2.0;
15 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
// return statement below:
return sum;
}
{
A a=new A();
System.out.println(a.RR(5.5, 6.5));
}
Output:
6.0
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 you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.
16 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
class. You can use the same fields and methods already defined in the previous
class.
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.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
17 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
In java programming, multiple and hybrid inheritance is supported through interface
only.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
18 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
19 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
File: TestInheritance3.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
20 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Output
class Vehicle
void display()
{
}
21 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
class Test
{
small.display();
}
Output:
Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We
could access maxSpeed of base class in subclass using super keyword.
2. Use of super with methods: This is used when we want to call parent class
method. So whenever a parent and child class have same named methods then to
resolve ambiguity we use super keyword.
class Person
void message()
{
}
/* Subclass Student */
void message()
{
22 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
}
void display()
{
message();
super.message();
}
class Test
{
s.display();
}
Output:
This is student class
This is person class
In the above example, we have seen that if we only call method message() then, the
current class message() is invoked but with the use of super keyword, message() of
superclass could also be invoked.
3. Use of super with constructors: super keyword can also be used to access the
parent class constructor. One more important thing is that, ‘’super’ can call both
parametric as well as non parametric constructors depending upon the situation.
23 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Eg:
Here, Emp class inherits Person class so all the properties of Person will be inherited to
Emp by default. To initialize all the property, we are using parent class constructor from
child class. In such way, we are reusing the parent class constructor.
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
Output:
1 ankit 45000
Rules
1. super may only be used within a subclass constructor method
2. The call to superclass constructor must appear as the first statement
within the subclass constructor
3. The parameters in the super call must match the order and type of
instance variable declared in the super class
24 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
// Base Class
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
void show()
{
System.out.println("Child's show()");
}
}
class Main {
public static void main(String[] args)
{
Child obj = new Child();
obj.show();
}
}
Output:
Child's show()
1. variable
2. method
3. class
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
25 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
26 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
10. }
Output:Compile Time Error
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
1. Abstract class
2. Interface
From the example above, it is not possible to create an object of the Shape
class:
27 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
To access the abstract class, it must be inherited from another class.
// Abstract class
System.out.println("Drawing Rectangle");
class MyMainClass {
rect.draw();
Rules
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
class A{}
class B extends A{}
A a=new B();//upcasting
Eg:
class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
29 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
s=new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...
3. PROTECTED ACCESS
The visibility level of the protected field lies between the private and the package
access.
That is the protected access makes the field visible not only to all classes and
subclasses in the same package but also to subclasses in other package
Non subclasses in their packages cannot access the protected members
4. PRIVATE ACCESS
Enjoys high degree of protection.
They are accessible only within their own class
They cannot be inherited by their subclass and hence not visible in it.
5. Private protected Access
Visibility lies between protected access and private access
It makes the fields visible in all subclasses regardless of what package they are in.
These fields are not accessible by other classes in the same package
30 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Interface in Java
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.
Syntax
interface InterfaceName
variable declaration;
methods declaration;
Interface – keyword
IntefaceName – valid identifier
Variables are declared as constants:
Methods declaration will contain only list of methods without any body statements.
return-type methodName1(parameter-list);
o The class that implements interface must define the code for the method
31 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Implementing interface
Interfaces are used as “superclass” whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interface.
body of classname
interface printable{
void print();
}
class Sample implements printable{
public void print()
{System.out.println("Hello");}
public static void main(String args[]){
Sample obj = new Sample();
obj.print();
}
}
32 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Output:
Hello
interface Printable{
void print();
}
interface Showable{
void show();
}
class Sample implements Printable, Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
Sample obj = new Sample();
obj.print();
obj.show();
}
}
Output:Hello
Welcome
Output:
Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class TestTnterface, so there is no
ambiguity.
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}
}
34 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Output:
Hello
Welcome
35 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m