Java Class Tutorial – Nested, Abstract, Static, Final Class Tutorial For Beginners

Java Class Tutorial – Nested, Abstract, Static, Final Class Tutorial For Beginners from Coding compiler. Here you will learn about Java classes, Java class access control and different types of classes. Let’s start learning Java programming.

Java Class Tutorial For Beginners

  1. Java class
  2. Java class access control
  3. Java class variable
  4. Java nested class
  5. Java abstract class
  6. Java variable type
  7. Java static final

Java Class Tutorial

 

The class defines a new data type.

This new type can be used to create this type of object.

A class is a template for an object and an object is an instance of a class.

Java Class Syntax

The general form of the class definition is as follows:

Class classname {
 Type instance-variable1;
 Type instance-variable2;
 // …
  type instance-variableN;


 Type methodname1(parameter-list) {
   // body of method
  }
 Type methodname2(parameter-list) {
   // body of method
  }
  // …
  type methodnameN(parameter-list) {
   // body of method
  }
}

 

Declare a class using the class keyword.

The methods and variables defined in the class are called class members.

Variables defined in a class are called instance variables because each instance of the class contains its own copy of those variables.

The data of one object is independent and unique to the data of another object.

Java Class Example

Here is a Box class called, which defines three member variables: width, height and depth.


Class Box {
    int width;
    int height;
    int depth;
}

Java object

When you create a class, a new data type is created. You can use this type to declare objects of this type.

Creating a class object is a two-step process.

  • A variable that declares a class type.
  • Use the new operator to dynamically allocate the memory of an object.

The following line is used to declare an object of type Box:

Box mybox = new Box();

 

This statement combines these two steps. It can be rewritten like this to show each step more clearly:

Box mybox; // declare reference to object
Mybox = new Box(); // allocate a Box object

 

The first line declares mybox a Box reference as an object of the type. After this line is executed, it mybox contains the value null. Null means that the mybox actual object has not been pointed to.

Trying to use mybox it at this time will result in an error.

The next line assigns an actual object and assigns a reference to mybox. After the second line is executed, you can use mybox as a Box object.

myboxSave the memory address of the actual Box object.

The class defines a new data type. In this case, the new type is called Box. To create an Box object, you would use the following statement:


Class Box {
  int width;
  int height;
  int depth;
}
Public class Main {
  public static void main(String args[]) {
   Box myBox = new Box();
   myBox.width = 10;

   System.out.println( “myBox.width:” +myBox.width);
 }
}

myBox Is Box an example. mybox contains your own copy of each instance variable width, height and depth is defined by the class. To access these variables, you will use the dot ( . ) operator.

Mybox.width = 10;

 

This statement assigns the width from the mybox object to 10. This is a Box complete program that uses classes:

Any attempt to use an empty mybox will result in a compile-time error.

Class box {
 Int width;
 Int height;
 Int depth;
}

Public class Main {
  public static void main(String args[]) {
   Box myBox;
   myBox.width = 10;
 }
}

 

If you try to compile the above code, you will get the following error message from the Java compiler.

Java instanceof operator

Java provides the runtime operator instanceof to check the object’s class type.

The instanceof operator has the following general form:

Object instanceof type

 

The following program demonstrates instanceof:


Class A {
}

Class B {
}

Class C extends A {
}

Class D extends A {
}

Public class Main{
  public static void main(String args[]) {
   A a = new A();
   B b = new B();
   C c = new C();
   D d = new D();

   If (a instanceof A)
     System.out.println( “a is instance of A” );
    if (b instanceof B)
     System.out.println( “b is instance of B” );
    if (c instanceof C)
     System.out.println( “c is instance of C” );
    if (c instanceof A)
     System.out.println( “c can be cast to A” );

   If (a instanceof C)
     System.out.println( “a can be cast to C” );

   A ob;
   Ob = d; // A reference to d
    System.out.println( “ob now refers to d” );
    if (ob instanceof D)
     System.out.println( “ob is instance of D” );

   Ob = c; // A reference to c
    System.out.println( “ob now refers to c” );
    if (ob instanceof D)
     System.out.println( “ob can be cast to D” );
    else
     System.out.println( “ob cannot be cast to D” );

   If (ob instanceof A)
     System.out.println( “ob can be cast to A” );
    // all objects can be cast to Object
   if (a instanceof Object)
     System.out.println( “a may be cast to Object” );
    if (b instanceof Object)
     System.out.println( “b may be cast to Object” );
    if (c instanceof Object)
     System.out.println( “c may be cast to Object” );
    if (d instanceof Object)
     System.out.println( “d may be cast to Object” );
 }
}

Java Tutorial – Java Class Access Control

 

We can control the access level of class member variables and methods by accessing the specifier.

Java’s access specifiers are public, private, protected, and default access levels.

level

  • Public class members can be accessed through any other code.
  • Private class members can only be accessed in their class.
  • The default access class member does not have an access specifier. The default functionality of a class can be accessed by any class in the same package.
  • The protected property of a class can be used for all classes and their subclasses in the same package (such as the default).

Protected features are easier to access than the default features.

To understand the impact of public and private access, consider the following procedure:


Class Test {
  int a;         // default access
 public int b; // public access
 private int c; // private access
 // methods to access c
 void setc( int i) {
   c = i;
 }
 Int getc() {
    return c;
 }
}
Public class Main {
  public static void main(String args[]) {
   Test ob = new Test();
   Ob.a = 1;
   Ob.b = 2;
   // This is not OK and will cause an error
   // ob.c = 100; // Error!
   // You must access c through its methods
    ob.setc(100); // OK
    System.out.println( “a , b, and c: ” + ob.a +
         ” ” + ob.b + ” ” + ob.getc());
 }
}

Member access and inheritance

Subclasses cannot access private members of the superclass. For example, consider the following simple class hierarchy. If you try to compile the following program, you will receive an error message.


Class A {
  private int j; // private to A
}
class B extends A {
  int total;

 Void sum() {
   Total = j; // ERROR, j is not accessible here
  }
}

Java access matrix

The following table shows the Java access matrix. It means barrier-free, meaningless and inaccessible.

position private No modifier protection public
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
The same package is not a subclass No Yes Yes Yes
Different buns No No Yes Yes
Different packages are not subclasses No No No Yes

Access modifiers and their targets

Not all modifiers can be applied to all features. Top-level classes may not be protected. The method may not be short-lived. Static can be applied to free-floating code blocks.

The table below shows all possible combinations of functions and modifiers. Yes means that we can use this modifier to control access to the corresponding entity.

Modifier class variable method Constructor Code block
Public Yes Yes Yes Yes No
Protected No Yes Yes Yes No
Empty accessor Yes Yes Yes Yes Yes
Private No Yes Yes Yes No
Final Yes Yes Yes No No
Abstract Yes No Yes No No
Static No Yes Yes No Yes
Native No No Yes No No
Transient No Yes No No No
Volat No Yes No No No
Synchronized No No Yes No Yes

Java Tutorial – Java Class Variables

Three types of variables

Java supports three different lifetime variables:

  • Member variables
  • Method local variable
  • Static variable

Class member variable

Creates a member variable of the class when the instance is created and is destroyed when the object is destroyed. All member variables that are not explicitly assigned a value are automatically assigned an initial value during the declaration. The initialization value of a member variable depends on the type of the member variable.

The following table lists the initialization values for member variables:

Element type Initial value
Byte 0
Short 0
Int 0
Long 0L
Flo 0.0f
Double 0.0d
Char “\u0000”
Boolean False
Object reference Null

In the following example, the variable x is set to 20 when the variable is declared.

Public class Main{
  Int x = 20;
}

 

If you do not set them, the following example shows the default value.

Class MyClass {
  int i;
  Boolean b;
 Float f;
 Double d;
 String s;

 Public MyClass() {
   System.out.println( “i=” + i);
   System.out.println( “b=” + b);
   System.out.println( “f=” + f);
   System.out.println( “d=” + d);
   System.out.println( “s=” + s);
 }

}

Public class Main {
  public static void main(String[] argv) {
    new MyClass();

 }
}

Example of a method local variable

The automatic variable of the method creates a method at the time of the entry and only exists during the execution of the method. Automatic variables can only be accessed when this method is executed. (One exception to this rule is the inner class).

Automatic variables (method local variables) are not initialized by the system. Automatic variables must be explicitly initialized before use. For example, this method won’t compile:

Public class Main{
    public int wrong() {
      int i;
      return i+5;
   }

}

Class variable (static variable)

Here is just a copy of a class variable that exists regardless of the number of instances of that class. Static variables are initialized when the class is loaded; here, when the Main class is loaded, y will be set to 30.

Public class Main{
  static int y = 30;
}

 

Java this keyword

this reference the current object.

this can be used in any method to reference the current object.

The following code shows how to use the this keyword.

// A use of this.
Rectangle( double w, double h) {
   This.width = w; // this is used here
    this.height = h;
}

 

Hidden instance variables and this

Use this referenced hidden instance variables.

Member variables and method parameters can have the same name. In this case, we can use it to reference member variables.

Rectangle(double width, double height) {
   This.width = width;
   This.height = height;
}

 

The following example shows how to use this reference instance variable.

Class Person{
    private String name;


   Public Person(String name) {
       This.name = name;
   }
   Public String getName() {
        return name;
   }
   Public void setName(String name) {
       This.name = name;
   }
}
Public class Main{
    public static void main(String[] args) {
       Person person = new Person( “Java” );
       System.out.println(person.getName());
       person.setName( “new name” );
       System.out.println(person.getName());
   }
}

Java Tutorial – Java Nesting Classes

 

A class declared outside of any class is a top-level class. A nested class is a class that is declared as a member of another class or scope.

There are four nested classes:

  • Static member class
  • Non-static member class
  • Anonymous class
  • Local class

Java anonymous class

Anonymous classes are classes that have no name and are declared at the same time. You can instantiate an anonymous class where specifying an expression is legal.

An anonymous class instance can only access local final variables and final parameters.

How to define an anonymous class?

Abstract class People {
  abstract void speak();
}

Public class Main {
  public static void main( final String[] args) {
    new People() {
     String msg = “test” ;

     @Override
     Void speak() {
       System.out.println(msg);
     }
   }.speak();
 }
}

Java anonymous class example

The following code declares and instantiates an anonymous class that implements the interface.

Interface People {
  abstract void speak();
}

Public class Main {
  public static void main( final String[] args) {
    new People() {
     String msg = (args.length == 1) ? args[0] : “nothing to say” ;

     @Override
     Public void speak() {
       System.out.println(msg);
     }
   }.speak();
 }
}

Java local class

A local class is a class declared anywhere in a local variable. Local and local variables have the same scope.

A local class has a name that can be reused. The local class instance can access the local final variables and final parameters of the surrounding scope.

Java local class

Class MyClass {
  void myMethod( final int x) {
    final int y = x;
   
   Class LocalClass {
      int a = x;
      int b = y;
   }
   
   LocalClass lc = new LocalClass();
   System.out.println(lc.a);
   System.out.println(lc.b);
 }
}

Public class Main {
  public static void main(String[] args) {
   MyClass ec = new MyClass();
   ec.myMethod(10);
 }
}

Java Local Class Example – 2

The following code declares an Iterator interface and an Iter inner class.

Class Item{
  private String name;
  private String value;
 
 Public Item(String n, String v){
   Name = n;
   Value = v;
 }
 Public String toString(){
    return name + value;
 }
}

Interface Iterator {
  boolean hasMoreElements();

 Object nextElement();
}

Class ItemManager {
  private Item[] itemArray;
  private int index = 0;

 ItemManager( int size) {
   itemArray = new Item[size];
 }

 Iterator iterator() {
   Class Iter implements Iterator {
      int index = 0;

     @Override
     Public boolean hasMoreElements() {
        return index < itemArray.length;
     }

     @Override
     Public Object nextElement() {
        return itemArray[index++];
     }
   }
   Return new Iter();
 }

 Void add(Item item) {
   itemArray[index++] = item;
 }
}

Public class Main {
  public static void main(String[] args) {
   ItemManager itemManager = new ItemManager(5);
   itemManager.add( new Item( “#1” , “A” ));
   itemManager.add( new Item( “#2” , “B” ));
   itemManager.add( new Item( “#3” , “C” ));
   Iterator iter = itemManager.iterator();
   While (iter.hasMoreElements()){
     System.out.println(iter.nextElement());
   }
     
 }
}

Java member class

The member class is a member of the closed class. Each instance of a member class is associated with an instance of a closed class.

Instance methods of member classes can call instance methods to enclose classes and access non-static fields of closed-class instances.

The following code has a named EnclosingClassexternal class and a non-static member class named EnclosedClass.

Class EnclosingClass {
  private int outerVariable;

 Private void privateOuterMethod() {
   System.out.println(outerVariable);
 }

 Class EnclosedClass {
    void accessEnclosingClass() {
     outerVariable = 1;
     privateOuterMethod();
   }
 }
}

Public class Main {
  public static void main(String[] args) {
   EnclosingClass ec = new EnclosingClass();
   Ec.new EnclosedClass().accessEnclosingClass(); // Output: 1
  }
}

Java member class example – 3

The following code uses the inner class ItemList to store the project.

Class Item {
  private String name;
  private String desc;

 Item(String name, String desc) {
   This.name = name;
   This.desc = desc;
 }

 String getName() {
   Return name;
 }

 String getDesc() {
   Return desc;
 }

 @Override
 Public String toString() {
    return “Name = ” + getName() + “, Desc = ” + getDesc();
 }
}

Class ItemManager {
  private ItemList itemList;
  private int index = 0;

 ItemManager() {
   itemList = new ItemList(2);
 }

 Boolean hasMoreElements() {
    return index < itemList.size();
 }

 Item nextElement() {
   Return itemList.get(index++);
 }

 Void add(Item item) {
   itemList.add(item);
 }

 Private class ItemList {
    private Item[] itemArray;
    private int index = 0;

   ItemList( int initSize) {
     itemArray = new Item[initSize];
   }

   Void add(Item item) {
      if (index >= itemArray.length) {
       Item[] temp = new Item[itemArray.length * 2];
        for ( int i = 0; i < itemArray.length; i++)
         Temp[i] = itemArray[i];
       itemArray = temp;
     }
     itemArray[index++] = item;
   }

   Item get( int i) {
      return itemArray[i];
   }

   Int size() {
      return index;
   }
 }
}

Public class Main {
  public static void main(String[] args) {
   ItemManager itemManager = new ItemManager();
   itemManager.add( new Item( “1” , “A” ));
   itemManager.add( new Item( “2” , “B” ));
   itemManager.add( new Item( “3” , “C” ));
    while (itemManager.hasMoreElements())
     System.out.println(itemManager.nextElement());
 }
}

Java member class example – 4

The following procedure shows how to define and use internal classes.


Class Outer {
  int outer_x = 100;
  void test() {
   Inner inner = new Inner();
   Inner.display();
 }
 Class Inner {
    void display() {
     System.out.println( “display: outer_x = ” + outer_x);
   }
 }
}
Public class Main {
  public static void main(String args[]) {
   Outer outer = new Outer();
   Outer.test();
 }
}

Java member class example – 5

Internal class members can only be accessed in inner classes and may not be used by external classes. If you try to compile the following code, you will receive an error message.


Public class Main {
  int outer_x = 100;
  // this is an inner class
 class Inner {
    int y = 10; // y is local to Inner

   void display() {
     System.out.println( “display: outer_x = ” + outer_x);
   }
 }

 Void showy() {
   System.out.println(y);
 }
}

Java static member class

A static member class is a static member of a closed class. Static member classes cannot access instance fields that contain classes and call their instance methods.

Static members can access static fields that contain classes and call their static methods, including private fields and methods.

The following code has a static member class declaration.

Class Demo {
  public static void main(String[] args) {
   Main.EnclosedClass.accessEnclosingClass();
   Main.EnclosedClass ec = new Main.EnclosedClass();
   ec.accessEnclosingClass2();
 }
}

Class Main {
  private static int outerVariable;

 Private static void privateStaticOuterMethod() {
   System.out.println(outerVariable);
 }

 Static void staticOuterMethod() {
   EnclosedClass.accessEnclosingClass();
 }

 Static class EnclosedClass {
    static void accessEnclosingClass() {
     outerVariable = 1;
     privateStaticOuterMethod();
   }

   Void accessEnclosingClass2() {
     staticOuterMethod();
   }
 }
}

 

A static member class can declare multiple implementations of its closed class.

Java static member class example – 6

The following code declares a Rectangleclass that uses static member classes to provide Rectangleimplementations for different data types, one for double type and one for float type.

Abstract class Rectangle {
  abstract double getX();

 Abstract double getY();

 Abstract double getWidth();

 Abstract double getHeight();

 Static class Double extends Rectangle {
    private double x, y, width, height;

   Double( double x, double y, double width, double height) {
     This.x = x;
     This.y = y;
     This.width = width;
     This.height = height;
   }

   Double getX() {
      return x;
   }

   Double getY() {
      return y;
   }

   Double getWidth() {
      return width;
   }

   Double getHeight() {
      return height;
   }
 }

 Static class Float extends Rectangle {
    private float x, y, width, height;

   Float( float x, float y, float width, float height) {
     This.x = x;
     This.y = y;
     This.width = width;
     This.height = height;
   }

   Double getX() {
      return x;
   }

   Double getY() {
      return y;
   }

   Double getWidth() {
      return width;
   }

   Double getHeight() {
      return height;
   }
 }

 Private Rectangle() {
 }

 Boolean contains( double x, double y) {
    return (x >= getX() && x < getX() + getWidth()) && (y >= getY() && y < getY() + getHeight());
 }
}

Public class Main {
  public static void main(String[] args) {
   Rectangle r = new Rectangle.Double(10.0, 10.0, 20.0, 30.0);
   r = new Rectangle.Float(10.0f, 10.0f, 20.0f, 30.0f);
 }
}

 

Java Tutorial – Java Abstract Class

 

Abstract classes are abstract ideas or concepts. For example, an int data type is a specific data type, and a double is another data type specific data type. They are all numbers. The numbers here are an abstract concept. Shape is another example. We can have spare, rectangular or triangular or round shapes. They are all concrete, and the shape is an abstract class.

In Java, we use abstract classes to define abstract concepts. Abstract concepts must have some abstraction. For example, the abstract concept is Shape, and the abstract aspect is how to calculate the area. Abstract concepts become abstract classes in Java and abstract aspects become abstract methods.

Java Abstract Class Explanation

You can ask to override some method abstract type modifiers by specifying subclasses. To declare an abstract method, use the following general form:

Abstract type name(parameter-list);

 

The abstract method has no method body. Any class that contains one or more abstract methods must also be declared as abstract.

Abstract class MyAbstractClass{
   abstract type name(parameter-list);
}

 

Here is an abstract class, followed by a class that implements its abstract methods.


Abstract class MyAbstractClass {
  abstract void callme();

 Void callmetoo() {
   System.out.println( “This is a concrete method.” );
 }
}

Class B extends MyAbstractClass {
  void callme() {
   System.out.println( “B”s implementation of callme.” );
 }
}

Public class Main {
  public static void main(String args[]) {
   B b = new B();
   B.callme();
   B.callmetoo();
 }
}

Java Abstract Class Example

The following code defines the Shape class as abstract.  The shape class has an abstract method called area(). RectangleThe class extends the abstract class Shape and implements the area() method for itself.


Abstract class Shape {
  double height;
  double width;

 Shape( double a, double b) {
   Height = a;
   Width = b;
 }
 Abstract double area();
}

Class Rectangle extends Shape{
 Rectangle( double a, double b) {
    super (a, b);
 }
 Double area() {
   System.out.println( “Inside Area for Rectangle.” );
    return height * width;
 }
}
Class Triangle extends Shape{
 Triangle( double a, double b) {
    super (a, b);
 }
 Double area() {
   System.out.println( “Inside Area for Triangle.” );
    return height * width / 2;

 }
}

Public class Main {
  public static void main(String args[]) {
   Rectangle r = new Rectangle(10, 5);
   Triangle t = new Triangle(10, 8);

   Shape figref;

   Figref = r;
   System.out.println( “Area is ” + figref.area());

   Figref = t;
   System.out.println( “Area is ” + figref.area());
 }
}

Java Tutorial – Java Variable Type

Java object reference variable

Object reference variables work differently when allocation occurs.

E.g,

Box b1 = new Box();
Box b2 = b1;

 

After execution of the fragment, b1and b2will point to the same object.

The assignment of b1 to b2 does not allocate any memory or copy any part of the original object. It simply makes b2 point to the same object as b1. Therefore, any changes made to the object through b2 will affect the object referenced by b1.

Subsequent assignment to b1 will simply remove b1 from the original object without affecting the object or affecting b2.

E.g:

Box b1 = new Box();
Box b2 = b1;
// …
B1 = null;

 

Here, b1 is set to null, but b2 still points to the original object.

Java object reference variable


Class Box {
  int width;
  int height;
  int depth;
}

Public class Main {
  public static void main(String args[]) {
   Box myBox1 = new Box();
   Box myBox2 = myBox1;

   myBox1.width = 10;

   myBox2.width = 20;

   System.out.println( “myBox1.width:” + myBox1.width);
   System.out.println( “myBox2.width:” + myBox2.width);
 }
}

Java method parameter passing

When a parameter is passed to a method, it can be passed by value or reference. Pass-by-Value copies the value of the parameter into the parameter. Changes made to parameters have no effect on the parameters. Pass a parameter by reference to pass a reference to the parameter. Changes made to the parameters will affect the parameters.

When a simple primitive type is passed to a method, it is done by using call-by-value. Objects are passed by using a call reference.

The following program uses “pass value.”


Class Test {
  void change( int i, int j) {
   i *= 2;
   j /= 2;
 }
}
Public class Main {
  public static void main(String args[]) {
   Test ob = new Test();

   Int a = 5, b = 20;

   System.out.println( “a and b before call: ” + a + ” ” + b);

   Ob.change(a, b);

   System.out.println( “a and b after call: ” + a + ” ” + b);
 }
}

Java method parameter passing example

In the following program, objects are passed by reference.


Class Test {
  int a, b;
 Test( int i, int j) {
   a = i;
   b = j;
 }
 Void meth(Test o) {
   Oa *= 2;
   Ob /= 2;
 }
}
Public class Main {
  public static void main(String args[]) {
   Test ob = new Test(15, 20);

   System.out.println( “ob.a and ob.b before call: ” + ob.a + ” ” + ob.b);

   Ob.meth(ob);

   System.out.println( “ob.a and ob.b after call: ” + ob.a + ” ” + ob.b);
 }
}

Java Tutorial – Java Static Final

Java static keyword

Static class members can be used independently of any object of the class.

Static members can be used by themselves without reference to specific instances.

Here is how to declare static methods and stati cvariables.

Static int intValue;

Static void aStaticMethod(){
}

 

limit

There are several limitations to the method declared as static:

  • They can only call other static methods.
  • They can only access static data.
  • They cannot quote this or super in any way.

All instances of a class share the same static variable. You can declare a static block to initialize a static variable. When the class is first loaded, the static block is only called once.

The following example shows a class with static methods


Public class Main {
  static int a = 3;
  static int b;

 Static void meth( int x) {
   System.out.println( “x = ” + x);
   System.out.println( “a = ” + a);
   System.out.println( “b = ” + b);

 }

 Public static void main(String args[]) {
   Main.meth(42);
 }
}

example

The following example shows a class with static variables.


Public class Main {
    static int a = 3;
    static int b;
}

 

We can refer to the static variables defined above as follows:

Main.a

 

The following example shows a class with a static initialization block.

Public class Main {

 Static int a = 3;

 Static int b;

 Static {
   System.out.println( “Static block initialized.” );
   b = a * 4;
 }
}

Java final keyword

The final variable cannot be modified. The final variable must be initialized at the time of declaration. The final variable is basically a constant.

Final variable


Public class Main {
  final int FILE_NEW = 1;
  final int FILE_OPEN = 2;
}

Prevent coverage

Methods declared as final cannot be overridden.


Class Base {
  final void meth() {
   System.out.println( “This is a final method.” );
 }
}

Class B extends A {
  void meth() { // ERROR! Can”t override.

   System.out.println( “Illegal!” );

 }
}

 

If you try to compile the above code, the compiler will generate the following error.

Related Java Tutorials & Interview Questions

Related Java Tutorials & Interview Questions
Introduction to Java Programming Core Java Multiple Choice Questions
Java Keywords Tutorial For Beginners 21 Aricent Java Interview Questions
Java Data Types Tutorial For Beginners 53 Accenture Java Interview Questions
Java Operators Tutorial For Beginners 399 Core Java Interview Questions
Java Control Flow Statements Tutorial 581 Advanced Java Interview Questions
Java Performance Tuning Tips 60 Java Multiple Choice Questions And Answers

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here