Basics of Java
Basics of Java
A class in Java is a set of objects that share common characteristics and common properties. It is a
user-defined blueprint or prototype from which objects are created. For example, Student is a class
while a particular student named Ravi is an object.
• Class is not a real-world entity. It is just a template or blueprint, or a prototype from which
objects are created.
o Data member
o Method
o Constructor
o Nested Class
o Interface
data member;
method;
constructor;
nested class;
interface;
• Modifiers: A class can be public or has default access (Refer this for details).
• Class name: The name should begin with an initial letter (capitalized by convention).
• Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
• Same Name as the Class: A constructor has the same name as the class in which it is defined.
• No Return Type: Constructors do not have any return type, not even void. The main purpose
of a constructor is to initialize the object, not to return a value.
• Automatically Called on Object Creation: When an object of a class is created, the constructor
is called automatically to initialize the object’s attributes.
• Used to Set Initial Values for Object Attributes: Constructors are primarily used to set the
initial state or values of an object’s attributes when it is created.
Example: This program demonstrates how a constructor is automatically called when an object is
created in Java.
// Constructor
import java.io.*;
// Driver Class
class A {
// Constructor
Geeks()
super();
System.out.println("Constructor Called");
// main function
A a1 = new A();
Output
Constructor Called
Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a
default constructor (constructor with no arguments) if your class doesn’t have any.
The below table demonstrates the key difference between Java Constructor and Java Methods.
Constructors must have the same name as the Methods can have any valid
Name class name name
Now let us come up with the syntax for the constructor being invoked at the time of object or
instance creation.
class A{
…….
// A Constructor
A() {
…….
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an
overloaded constructor), if you don’t type in the call to super in your constructor the compiler will
provide you with a non-argument call to super at the first line of your code, the super constructor must
be called to create an object:
Note: If you think your class is not a subclass it actually is, every class in Java is the subclass of a
class object even if you don’t say extends object in your class definition.
Constructors play a very important role, it ensures that an object is properly initialized before use.
Without constructors:
Each time an object is created using a new() keyword, at least one constructor (it could be the default
constructor) is invoked to assign initial values to the data members of the same class. Rules for writing
constructors are as follows:
• The constructor(s) of a class must have the same name as the class name in which it resides.
• Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.
Now is the correct time to discuss the types of the constructor, so primarily there are three types of
constructors in Java are mentioned below:
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Explicit Default Constructor: If we define a constructor that takes no parameters, it’s called an
explicit default constructor. This constructor replaces the one the compiler would normally
create automatically. Once you define any constructor (with or without parameters), the
compiler no longer provides the default constructor for you.
Example: This program demonstrates the use of a default constructor, which is automatically called
when an object is created.
// Default Constructor
import java.io.*;
// Driver class
class A {
// Default Constructor
A() {
System.out.println("Default constructor"); }
// Driver function
A a1 = new A();
Output
Default constructor
Note: Default constructor provides the default values to the object like 0, null, false etc. depending on
the type.
Example: This program demonstrates the use of a parameterized constructor to initialize an object’s
attributes with specific values.
import java.io.*;
class A {
String name;
int id;
this.name = name;
this.id = id;
class B
Output
There are no “return value” statements in the constructor, but the constructor returns the current class
instance. We can write ‘return’ inside a constructor.
Unlike other constructors copy constructor is passed with another object which copies the data
available from the passed object to the newly created object.
Note: In Java,there is no such inbuilt copy constructor available like in other programming languages
such as C++, instead we can create our own copy constructor by passing the object of the same class
to the other instance(object) of the class.
Example: This example, demonstrates how a copy constructor can be used to create a new object by
copying the values of another object’s attributes.
import java.io.*;
class A {
String name;
int id;
// Parameterized Constructor
this.name = name;
this.id = id;
// Copy Constructor
A(A obj2)
this.name = obj2.name;
this.id = obj2.id;
class A {
System.out.println("First Object");
A a2 = new A(a1);
System.out.println(
Output
First Object
Constructor Overloading
When we create more than one constructors in same class provided they have different umber of
arguments / different type of argument.
package contructor;
public class B {
B(){
System.out.println(1);
B(int x){
System.out.println(10);
B b1=new B();
B b2=new B(100);
}
}
Output
Constructor Chaining
Constructor chaining is the process of calling one constructor from another constructor with respect
to current object.
One of the main use of constructor chaining is to avoid duplicate codes while having multiple
constructor (by means of constructor overloading) and make code more readable.
• Within same class: It can be done using this() keyword for constructors in the same class
• From base class: by using super() keyword to call the constructor from the base class.
Constructor chaining occurs through inheritance. A sub-class constructor’s task is to call super class’s
constructor first. This ensures that the creation of sub class’s object starts with the initialization of the
data members of the superclass. There could be any number of classes in the inheritance chain. Every
constructor calls up the chain till the class at the top is reached.
This process is used when we want to perform multiple tasks in a single constructor rather than
creating a code for each task in a single constructor we create a separate constructor for each task and
make their chain which makes the program more readable.
Example:
package constructor_chaining;
//another constructor
public class A {
System.out.println(x);
System.out.println(y);
}
A(int x){
this(1000,2000);
A(){
this(100);
A a1=new A();
Java Methods
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can
also create your own methods to perform certain actions:
Example
// code to be executed
Example Explained
• static means that the method belongs to the Main class and not an object of the Main class.
You will learn more about objects and how to access methods through objects later in this
tutorial.
• void means that this method does not have a return value. You will learn more about return
values later in this chapter
• Call a Method
• To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
• In the following example, myMethod() is used to print a text (the action),
when it is called:
Example
myMethod();
Modifiers
Access Specifier / Access Modifiers
1. private
2. default
3. protected
4. public
Same package
subclass NO Yes yes yes
Same package
non subclass NO Yes yes yes
different
package No No yes yes
subclass
different
package non No No No yes
subclass
Private:
a. private members are the class are accessible in the same class
Example 1:
package p1;
public class A {
System.out.println("From test");
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
10
From test
Example 2:
package p1;
public class A {
System.out.println("From test");
package p1;
B b1 = new B();
System.out.println(b1.i);
b1.test();
Output:
error
Example 3:
package p1;
public class A {
System.out.println("From test");
package p1;
public class B {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
error
Example 4:
package p1;
public class A {
private int i = 10;
System.out.println("From test");
package p2;
import p1.A;
C c1 = new C();
System.out.println(c1.i);
c1.test();
Output:
Error
Note: private members cannot be accessed in different package non sub class
Example 5:
package p1;
public class A {
System.out.println("From test");
package p2;
import p1.A;
public class C {
A a1 = new A();
System.out.println(a1.i);
a1.test();
}
}
Output:
Error
Important Note:
Private members are accessible only in same class, outside that class
private members cannot be used
These members are accessible only in same package, outside the package tese
members cannot be accessed
Example 1:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
10
From Test
Example 2:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
package p1;
B b1 = new B();
System.out.println(b1.i);
b1.test();
Output:
10
From Test
Example 3:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
package p1;
public class B {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
10
From Test
Example 4:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
Example 5:
package p1;
public class A {
int i = 10;
void test(){
System.out.println("From Test");
package p2;
import p1.A;
public class C {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Example 1:
package p1;
public class A {
System.out.println("From Test");
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
10
From Test
Example 2:
package p1;
public class A {
System.out.println("From Test");
package p1;
B b1 = new B();
System.out.println(b1.i);
b1.test();
Example 3:
package p1;
public class A {
System.out.println("From Test");
package p1;
public class B {
A a1 = new A();
System.out.println(a1.i);
a1.test();
Example 4:
package p1;
public class A {
System.out.println("From Test");
package p2;
import p1.A;
C c1 = new C();
System.out.println(c1.i);
c1.test();
Output:
10
From Test
Example 5:
package p1;
public class A {
System.out.println("From Test");
package p2;
import p1.A;
public class C{
A a1 = new A();
System.out.println(a1.i);
a1.test();
Output:
Error
Example 1:
package p1;
class A {
}
package p2;
import p1.A;
Output: Error
Note: