Classes and interfaces in Java

Examples illustrate Java classes and interfaces.


public class Demo {

	public static void main(String[] args) {
		Interface1 obj1 = new Class1();
		System.out.println(obj1.m1(1));
		
		Interface2 obj2 = (Interface2) obj1;
		System.out.println(obj2.m2(1));
		
		Class1 obj3 = new Class1();
		System.out.println(obj3.m1(1));
		System.out.println(obj3.m2(1));
		
		Class1 obj4 = new Class2();
		System.out.println(obj4.m1(1));
		System.out.println(obj4.m2(1));
		
		// can a variable of Class2 be assigned an
		// object of Class1? Of any of the interfaces? 
		// Do we need typcasting? 
		
		// If I have a method that takes Interface1, what can I pass to it?
		// If I have a method that takes Class1, what can I pass to it?
		// If I have a method that takes Class2, what can I pass to it?
		
		// What are abstract classes? 
		
		// what does equals take? 
		// what does it mean for an object to be comparable? iterable? 
	}
	
	static interface Interface1 {
		public int m1(int x);
	}
	
	static interface Interface2 {
		public int m2(int x);
	}
	
	static class Class1 implements Interface1, Interface2 {

		@Override
		public int m1(int x) {
			return x + 1;
		}

		@Override
		public int m2(int x) {
			return m3(x) + 2;
		}
		
		private int m3(int x) {
			return x * 3;
		}
		
		protected int m4(int x) {
			return x % 2;
		}
		
	}
	
	static class Class2 extends Class1 {
		public int m1(int x) {
			return m3(x - 1);
		}
		
		private int m3(int x) {
			return m4(x) * 2;
		}
	}

}

CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.