Class in java

Class

 

A class is a user-defined template or prototype from which objects are created.  It represents the set of properties or methods that are common to all objects of one type

 

Subclass

 

A subclass is a class that extends another class which is a superclass. Subclasses don't inherit the superclass's private member variables. Subclasses inherit those member variables declared with no access specifier as long as the subclass is in the same package as the superclass.

 

components  of a class

 

class declarations can include these, in order

> Modifiers define the access of the class such as public, or private.

> Class name with the initial letter capitalized by convention.

> SuperClass(if present) The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.

> Interface(if present) A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.

> The class body surrounded by braces {}.

A class in Java can contain Fields, Methods, Constructors, Blocks, Nested classes, and an interface

 

Syntax to declare a class

class { 
      field; 
      method;
  }

Syntax for a subclasss

public class X {

}

public class Y extends X {            

}

Here X is the superclass and Y is the subclass that extends X

 

Variables in a class

 

A class can contain any of the following variable types.

 
Local variables

 

Variables defined inside methods, constructors, or blocks are called local variables.

The variable will be declared and initialized within the method and destroyed when the method is completed.

 
Instance variables

 

Instance variables are variables within a class but outside any method.

These variables are initialized when the class is instantiated and can be accessed from inside any method, constructor or block of that particular class.

 
Class variables

 

Class variables are variables declared within a class, outside any method with the static keyword.

 

Usecase

public class Calculation {
    int z;
    public void addition(int x, int y) {
        z = x + y;
        System.out.println("The sum of the given numbers:" + z);
    }
    public void Subtraction(int x, int y) {
        z = x - y;
        System.out.println("The difference between the given numbers:" + z);
    }
}
public class MyCalculation extends Calculation {
    public void multiplication(int x, int y) {
        z = x * y;
        System.out.println("The product of the given numbers:" + z);
    }
    public static void main(String args[]) {
        int a = 20, b = 10;
        MyCalculation demo = new MyCalculation();
        demo.addition(a, b);
        demo.Subtraction(a, b);
        demo.multiplication(a, b);
    }
}

 

Output:

The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
 
 

 

Related Tutorials

Map