Access Modifiers – Key Points

Member Access Modifiers:

  • Methods and instance (non local) variables are known as “members.”
  • Members can use all four access levels: public, protected, default, and
    private.
  • Member access comes in two forms:
    • Code in one class can access a member of another class.
    • A subclass can inherit a member of its super class.
  • If a class cannot be accessed, its members cannot be accessed.
  • Determine class visibility before determining member visibility.
  • public members can be accessed by all other classes, even in other packages.
  • If a super class member is public, the subclass inherits it-regardless of
    package.
  • Members accessed without the dot operator (.) must belong to the same
    class.
  • this. always refers to the currently executing object.
  • this.aMethod() is the same as just invoking aMethod().
  • private members can be accessed only by code in the same class.
  • private members are not visible to sub classes, so private members cannot
    be inherited.
  • Default and protected members differ only when sub classes are involved:
    • Default members can be accessed only by classes in the same package.
    • protected members can be accessed by other classes in the same package, plus sub classes regardless of package.
    • protected = package + kids (kids meaning sub classes).
    • For sub classes outside the package, the protected member can be accessed only through inheritance; a subclass outside the package cannot access a protected member by using a reference to a super class instance.
    • A protected member inherited by a subclass from another package is not accessible to any other class in the subclass package, except for the subclass own sub classes.

Other Modifiers—Members:

  • final methods cannot be overridden in a subclass.
  • abstract methods are declared with a signature, a return type, and an optional throws clause, but they are not implemented.
  • abstract methods end in a semicolon – no curly braces.
  • Three ways to spot a nonabstract method:
    • The method is not marked abstract.
    • The method has curly braces.
    • The method MIGHT have code between the curly braces.
  • The first nonabstract (concrete) class to extend an abstract class must implement all of the abstract class’ abstract methods.
  • The synchronized modifier applies only to methods and code blocks.
  • synchronized methods can have any access control and can also be marked final.
  • abstract methods must be implemented by a subclass, so they must be inheritable. For that reason:
    • abstract methods cannot be private.
    • abstract methods cannot be final.
  • The native modifier applies only to methods.
  • The strictfp modifier applies only to classes and methods.

Invoke static methods

StringUtil.java

package com.sridhar;

public class StringUtil {
	public static String getFullName(String fName,String lName)
	{
		String fullName= fName+" "+lName;
		return fullName;
	}
}

TestStringUtil.java

package com.sridhar;
public class TestStringUtil {

	public static void main(String[] args) {
		//input
		String firstName = "Ramesh";
		String lastName = "Raja";

		//Business Logic
		String fullName=StringUtil.getFullName(firstName, lastName);

		//output
		System.out.println("FullName:"+fullName);

	}
}

Invoke non static methods using object

StringUtil.java

package com.sridhar;

public class StringUtil {
	public String getFullName(String fName,String lName)
	{
		String fullName= fName+" "+lName;
		return fullName;
	}
}

TestStringUtil.java

package com.sridhar;
public class TestStringUtil {

	public static void main(String[] args) {
		//input
		String firstName = "Ramesh";
		String lastName = "Raja";
		
		//Business Logic
		StringUtil strUtil = new StringUtil();
		String fullName=strUtil.getFullName(firstName, lastName);
				
		//output
		System.out.println("FullName:"+fullName);

	}
}

Overriding toString()

Student.java

package com.sridhar;

public class Student {
	private int id;
	private String name;

	public Student(int id, String name) {
		super();
		this.setId(id);
		this.setName(name);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Override
	public String toString() {

		return "Student [ID="+id+", NAME="+name+"]";
	}

}

 



TestStudentToString.java

package com.sridhar;

public class TestStudentToString {

	public static void main(String[] args) {
		Student student= new Student(101,"Sridhar");
		System.out.println("Student Details are");
		System.out.println(student);
	}

}

 

output:

Student Details are
Student [ID=101, NAME=Sridhar]



	

Sum of Integer using variable arguments

SumofIntegerUtil.java

package com.sridhar;
public class SumofIntegerUtil {
static int sumofInt=0;
public static int doSum(int... args) {

if(args.length>0)
{
int i;

for(i=0;i<args.length;i++)
{
sumofInt+=args[i];
}
}

return sumofInt;
}
}[/code]

<hr />

<h2>TestSumofInt.java</h2>
package com.sridhar;

import java.util.Scanner;

public class TestSumofInt {

	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args) throws ArrayIndexOutOfBoundsException {

		//input
		System.out.println("Enter the no.of arguments to calculate summation");
		int argsCount=sc.nextInt();

		//Business Logic
		int[] argsArray = new int[10];

		for(int i=0;i&lt;argsCount;i++)
		{
			argsArray[i]=sc.nextInt();
		}

		int sumofInt = SumofIntegerUtil.doSum(argsArray);

		//output
		System.out.println("Sum of the given values is:"+sumofInt);

	}

}

Var Args


package com.sridhar;

public class TestVarArgs {

public static void main(String... args) {

if(args.length>0)
{
System.out.println("Arguments that were passed to the program:");
for(String value:args)
{
System.out.println(value);
}
}

}

}

Numeric Literals

public class NumericLiteralExample {
public static void main(String[] args) {
int million = 1_000_000;
int billion = 1_000_000_000;
float ten_pct = 1_0f;
double exp = 1_234_56.78_9e2;
System.out.println(million);
System.out.println(billion);
System.out.println(ten_pct);
System.out.println(exp);
}
}

Datatype size

public class DeclarationsExample {
public static void main (String[] args) {
boolean BooleanVal = true; /* Default is false */

char charval = 'G'; /* Unicode UTF-16 */
charval = '\u0490'; /* Ukrainian letter Ghe(Ґ) */
byte byteval; /* 8 bits, -127 to 127 */
short shortval; /* 16 bits, -32,768 to 32,768 */
int intval; /* 32 bits, -2147483648 to 2147483647 */
long longval; /* 64 bits, -(2^64) to 2^64 - 1 */
float floatval = 10.123456F; /* 32-bit IEEE 754 */
double doubleval = 10.12345678987654; /* 64-bit IEEE 754 */
String message = "Darken the corner where you are!";
message = message.replace("Darken", "Brighten");
}
}

Command Line Arguments

public class PassingArguments {
public static void main(String[] args)
{
if(args.length > 0)
{
System.out.println("Arguments that were passed to the program: ");
for (String arg:args){
System.out.println(arg);
}
}
else
{
System.out.println("No arguments passed to the program.");
}
}
}

BigDecimal

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;

public class MonetaryCalculation {

public static void main(String[] args) {
// Run the currency calculation examples
calculateDollars();
}
/**
* Formats a double value into currency format and then returns it as
* a String
* @param value
* @return
*/
public static String formatDollars(double value) {
NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(Locale.US);
return dollarFormat.format(value);
}
public static void calculateDollars() {
BigDecimal currencyOne = new BigDecimal("25.65");
BigDecimal currencyTwo = new BigDecimal("187.32");
BigDecimal currencyThree = new BigDecimal("4.86");
BigDecimal result = null;
String printFormat = null;
// Add all three values
result = currencyOne.add(currencyTwo).add(currencyThree);
// Convert to double and send to formatDollars(), returning a String
printFormat = formatDollars(result.doubleValue());
System.out.println(printFormat);
// Subtract the first currency value from the second
result = currencyTwo.subtract(currencyOne);
printFormat = formatDollars(result.doubleValue());
System.out.println(printFormat);
}
}